Skip to content

Connect 7shifts to AI Agents: Sync Sales, Labor & Tip Reporting

Learn how to connect 7shifts to ai agents using Truto. Step-by-step guide to tool calling, API quirks, and autonomous workflows.

Sidharth Verma Sidharth Verma · · 10 min read
Connect 7shifts to AI Agents: Sync Sales, Labor & Tip Reporting

You want to connect 7shifts to an AI agent so your system can autonomously audit daily labor costs, resolve tip pool discrepancies, and sync time punches. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to build and maintain a custom REST integration from scratch.

Giving a Large Language Model (LLM) read and write access to your 7shifts instance requires strict data validation. A model cannot afford to hallucinate location IDs or guess at pagination cursors when handling payroll and scheduling data. If your team uses ChatGPT, check out our guide on connecting 7shifts to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting 7shifts to Claude. For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them to your agent framework.

This guide breaks down exactly how to fetch AI-ready tools for 7shifts, bind them natively to an LLM using frameworks like LangChain, LangGraph, CrewAI, or the Vercel AI SDK, and execute complex restaurant operations workflows. For a broader look at this design pattern, read our research on Architecting AI Agents: LangGraph, LangChain, and the SaaS Integration Bottleneck.

Why a Unified Tool Layer Matters for Agent Safety

Before writing a line of integration code, you must decide what layer your agent will interact with. This choice dictates the reliability and safety of your production system.

Direct API tools - mapping one tool directly to one raw 7shifts endpoint - look simple on paper, but they push provider-specific quirks directly into the LLM's context window. The model has to remember that time punch break updates must include the entire array state, or that analytics queries require specific date-string formats. Every one of those quirks is a hallucination waiting to happen.

A unified tool layer abstracts these endpoints behind a strict, predictable schema. Your agent sees 7_shifts_analytics_get_daily_sales_and_labor or list_all_7_shifts_shifts with deterministic JSON schemas. That provides three concrete safety wins:

  1. Smaller attack surface for hallucination. The LLM only ever chooses from stable function names and predefined parameters. It never invents query strings.
  2. Deterministic input validation. Every tool has a strict JSON schema. Invalid arguments are rejected before they ever hit the 7shifts API, so a broken tool call fails fast.
  3. Decoupled authentication. The agent framework never handles API keys or OAuth tokens. It simply requests an action, and the proxy layer handles the secure transport.

The Engineering Reality of the 7shifts API

Giving an LLM access to external data sounds simple in a prototype. You write a Node.js function that makes a fetch request and wrap it in an @tool decorator. In production against a complex labor management system, this approach collapses.

The 7shifts API introduces several specific integration challenges that break standard REST assumptions. If you hardcode these interactions into your agent, you will spend your sprints writing defensive integration code instead of improving your model's reasoning capabilities.

The Strict Organizational Hierarchy

7shifts models the physical reality of a restaurant or hospitality business. Its data model relies on a strict, cascading hierarchy: Company > Location > Department > Role.

You cannot simply create a shift for a user. An LLM must first resolve the user's ID, fetch the specific location ID, identify the department ID (e.g., Back of House), and select the role ID (e.g., Line Cook). If an agent attempts to assign a user to a shift using a role ID that does not belong to the specified department, the 7shifts API will reject the payload. Your agent needs access to directory tools to traverse this hierarchy sequentially before executing write operations.

Dangerous State Mutations on Time Punches

Updating existing records in 7shifts requires careful state management, particularly for time punches and breaks.

The API documentation explicitly dictates that when updating a time punch, breaks must always be included in their correct, complete state. Omitting an existing break from the update payload deletes that break entirely from the database. A stateless LLM is prone to sending partial updates - sending only the clock-out time and forgetting to include the midday meal break array. Without a proxy layer enforcing schema completeness, your agent will inadvertently delete legally mandated break records from payroll.

Forecast Overrides and Sync Intervals

When writing projected sales forecast overrides, 7shifts requires data to be pushed in specific 15-minute or 1-hour intervals. LLMs naturally struggle with generating continuous, perfectly formatted time-series arrays. Asking an agent to "override next week's sales forecast to $10,000 daily" requires the agent to calculate, format, and batch 96 individual 15-minute intervals per day.

Essential 7shifts Tools for AI Agents

Rather than exposing raw HTTP endpoints, we bind specific, high-leverage operations as tools. Here are the core 7shifts tools that enable autonomous labor and sales reporting operations.

7_shifts_analytics_get_daily_sales_and_labor

This tool retrieves a highly structured daily sales and labor report for a specific 7shifts company location. It returns both actual and projected metrics, including actual items sold, projected labor minutes, actual sales, actual labor cost, and Sales Per Man Hour (SPMH).

Contextual Usage: Agents use this tool to build end-of-day reconciliation reports. It is the primary data source for flagging locations that are missing their labor targets or bleeding margin due to unplanned overtime.

"Pull the daily sales and labor metrics for the Downtown location for yesterday. Calculate the variance between projected labor cost and actual labor cost, and flag it if the variance exceeds 5 percent."

list_all_7_shifts_shifts

Retrieves a paginated list of shifts for a company, filterable by location, department, role, user, and date range. The response includes start times, end times, attendance status, and late minutes.

Contextual Usage: Essential for auditing schedule adherence. Agents can chain this tool with time punch data to identify employees who consistently clock in late or miss scheduled shifts without entering time-off requests.

"Fetch all scheduled shifts for the Front of House department for the next 7 days. Identify any shifts that are currently unassigned and list the roles required to fill them."

list_all_7_shifts_time_punches

Lists raw time punches, including clock-in, clock-out, approved status, offline punches, and embedded break data.

Contextual Usage: This is the ground-truth tool for payroll generation. Agents use this to verify that actual hours worked match the scheduled shifts, and to flag punches that require manager approval before the payroll period closes.

"Retrieve all unapproved time punches for the Uptown location from last week. Cross-reference them with the scheduled shifts and highlight any punch where the employee clocked out more than 30 minutes after their scheduled end time."

7_shifts_tip_pool_reports_get_detailed

Retrieves a detailed tip pool report for a location over a specified date range. It breaks down tips per date and per employee, identifying unassigned tips and total distributions.

Contextual Usage: Tip pooling is notoriously complex and error-prone. Agents use this tool to autonomously audit weekly tip distributions, ensuring no tips are left unassigned and that manual overrides are documented.

"Generate a detailed tip pool report for the past two weeks at the flagship store. Identify any days where the unassigned tips balance is greater than zero and list the employees who received manual tip entries."

update_a_7_shifts_time_punch_by_id

Updates an existing time punch. Crucially, this tool handles the mutation of clock times, wages, and breaks.

Contextual Usage: Used when an agent is authorized to auto-correct missed punches based on manager Slack approvals or scheduling data. Because of the break state mutation quirk mentioned earlier, the agent must fetch the existing punch first, modify the JSON, and send the complete object back.

"The manager approved John's missed clock-out for yesterday at 11:00 PM. Fetch his open time punch for that shift and update the clock-out time, ensuring his 30-minute meal break is preserved in the record."

7_shifts_forecast_overrides_bulk_create_daily

Allows the agent to push bulk daily projected forecast overrides for a location. This sets the baseline for the labor scheduling engine.

Contextual Usage: When external factors (weather, local events, historical data) indicate a spike in traffic, an agent can autonomously adjust the sales forecast, which in turn alerts managers to schedule more labor.

"A major concert was just announced next door for Friday night. Bulk create a daily forecast override for Friday, increasing the projected sales by 40 percent based on our historical event baseline."

To view the complete inventory of available 7shifts tools, including detailed request schemas, parameter requirements, and return structures, visit the 7shifts integration page.

Workflows in Action

AI agents excel at executing repetitive, multi-step operations that currently trap restaurant managers in back-office administrative work. Here are two concrete workflows showing how an agent chains 7shifts tools to automate operations.

Use Case 1: The End-of-Day Labor vs. Sales Audit

Restaurant margins are made and lost daily. Waiting for end-of-week payroll reports is too late. A regional manager needs to know immediately if a store blew its labor budget.

"Run the end-of-day labor audit for the Eastside location for yesterday. Compare actual sales to projected sales, and calculate the actual labor percentage. If the labor percentage is above 28 percent, list all shifts from yesterday that incurred overtime."

Execution Steps:

  1. The agent calls list_all_7_shifts_locations to map 'Eastside' to its specific location_id.
  2. It calls 7_shifts_analytics_get_daily_sales_and_labor passing the location_id and yesterday's date. It extracts actual_sales and actual_labor_cost to calculate the percentage.
  3. Discovering the labor cost is 31 percent, the agent calls list_all_7_shifts_time_punches for yesterday, filtering for approved and unapproved punches.
  4. It parses the punches, identifies records where hourly_wage includes overtime multipliers, and formulates a summary report for the manager.

Use Case 2: Autonomous Tip Pool Reconciliation

Before finalizing payroll, finance teams must ensure that 100 percent of collected tips have been legally and accurately distributed according to the store's tip pool rules.

"Audit the tip pool for the Westside store for the payroll period ending Sunday. Flag any dates with unassigned tips. For any manual tip entries found, pull the employee's name and the amount."

Execution Steps:

  1. The agent calls 7_shifts_payroll_periods to get the exact start and end dates for the most recent period.
  2. It executes 7_shifts_tip_pool_reports_get_detailed using the date range and the Westside location_id.
  3. The agent scans the report_rows looking for unassigned_tips > 0.
  4. Identifying manual entries linked only to a user_id, the agent calls get_single_7_shifts_user_by_id to resolve the employee names, returning a clean discrepancy report to the finance channel.

Building Multi-Step Workflows

To execute these workflows in production, you need a robust agent loop. The agent must fetch the available Truto tools, bind them to the LLM, execute the chain of reasoning, and critically - handle HTTP rate limits.

Truto does not automatically retry, throttle, or apply backoff on rate limit errors. When the upstream 7shifts API returns an HTTP 429 (Too Many Requests), Truto passes that error directly to your caller. However, Truto normalizes the upstream rate limit information into standardized IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset). Your agent framework is responsible for catching the 429, reading the ratelimit-reset header, and applying the backoff.

Here is how to build this resilient loop using TypeScript and LangChain (though the exact same architectural pattern applies to CrewAI, LangGraph, or the Vercel AI SDK).

sequenceDiagram
    participant App as Agent Loop
    participant Truto as Truto /tools API
    participant Upstream as "7shifts API"

    App->>Truto: GET /integrated-account/{id}/tools
    Truto-->>App: Returns JSON Tool Schemas
    App->>App: bindTools() to LLM
    
    App->>Truto: Execute list_all_7_shifts_shifts
    Truto->>Upstream: GET /v2/company/{id}/shifts
    Upstream-->>Truto: 200 OK
    Truto-->>App: Shift Data
    
    App->>Truto: Execute 7_shifts_analytics_get_daily_sales_and_labor
    Truto->>Upstream: GET /v2/company/{id}/locations/{id}/daily_sales_and_labor
    Upstream-->>Truto: 429 Too Many Requests
    Truto-->>App: 429 Error (ratelimit-reset: 10)
    
    Note over App: Agent catches 429<br>Waits 10 seconds
    App->>Truto: Retry execution
    Truto->>Upstream: GET /v2/.../daily_sales_and_labor
    Upstream-->>Truto: 200 OK
    Truto-->>App: Sales Data

Step 1: Initialize the Tool Manager and Fetch Schemas

First, we instantiate the TrutoToolManager and fetch the proxy API schemas for the specific connected 7shifts account. This dynamically loads all allowed operations.

import { ChatOpenAI } from "@langchain/openai";
import { TrutoToolManager } from "truto-langchainjs-toolset";
 
// Initialize the Truto Tool Manager with your tenant access
const truto = new TrutoToolManager({
  apiKey: process.env.TRUTO_API_KEY,
});
 
async function runAgentWorkflow(prompt: string, integratedAccountId: string) {
  // Fetch all 7shifts tools available for this specific integrated account
  const tools = await truto.getTools(integratedAccountId);
 
  // Initialize the LLM
  const llm = new ChatOpenAI({
    modelName: "gpt-4o",
    temperature: 0,
  });
 
  // Bind the Truto tools to the model
  const llmWithTools = llm.bindTools(tools);
 
  let messages = [{ role: "user", content: prompt }];
  
  // Enter the agent reasoning loop
  await executeAgentLoop(llmWithTools, tools, messages);
}

Step 2: The Resilient Execution Loop

The core of an AI agent is a while loop. The model outputs a tool call, you execute the tool, append the result, and ask the model what to do next. This is where we must implement our 429 backoff logic.

async function executeAgentLoop(llmWithTools, tools, messages) {
  while (true) {
    // 1. Ask the model for the next step
    const response = await llmWithTools.invoke(messages);
    messages.push(response);
 
    // 2. If the model didn't call a tool, the workflow is complete
    if (!response.tool_calls || response.tool_calls.length === 0) {
      console.log("Final Output:", response.content);
      break;
    }
 
    // 3. Execute requested tools
    for (const toolCall of response.tool_calls) {
      const selectedTool = tools.find((t) => t.name === toolCall.name);
      
      let toolResult;
      try {
        // Execute the proxy API call via Truto
        toolResult = await selectedTool.invoke(toolCall.args);
      } catch (error) {
        // Handle normalized rate limit headers explicitly
        if (error.status === 429) {
          const resetSeconds = parseInt(error.headers.get('ratelimit-reset') || '60', 10);
          console.warn(`Rate limit hit. Waiting ${resetSeconds} seconds...`);
          
          await new Promise(resolve => setTimeout(resolve, resetSeconds * 1000));
          
          // Retry the tool execution post-backoff
          toolResult = await selectedTool.invoke(toolCall.args);
        } else {
          // Feed standard API errors back to the LLM so it can self-correct
          toolResult = `API Error: ${error.message}`;
        }
      }
 
      // Append the tool result to the conversation history
      messages.push({
        role: "tool",
        tool_call_id: toolCall.id,
        content: JSON.stringify(toolResult),
      });
    }
  }
}

By feeding errors directly back into the messages array, if the agent hallucinates a department ID or formats a date incorrectly, the 7shifts API will return a 400 Bad Request via Truto. The agent reads the error description, realizes its mistake, and autonomously generates a corrected payload on the next iteration.

Moving from Manual Scripts to Autonomous Labor Ops

Connecting 7shifts to an AI agent transforms scheduling and payroll from a reactive manual process into a proactive, autonomous system. By utilizing a unified tool layer, you eliminate the massive engineering overhead of maintaining JSON schemas, handling pagination drift, and writing defensive error-handling logic for every endpoint.

Your engineers can focus on building better prompts and sophisticated agent logic, while the infrastructure layer handles the API complexity safely and deterministically.

More from our Blog