# LinkTime Private Admin MCP Server > Internal Model Context Protocol (MCP) server for autonomous AI agents. 45 tools across 12 domains. > Endpoint: POST /api/admin/agent-mcp > Authentication: Bearer token (agent API key) > Protocol: JSON-RPC 2.0 > Last updated: March 2026 ## Overview LinkTime's private admin MCP server gives autonomous AI agents scoped access to platform data and operations. Each agent authenticates with an API key that grants specific scopes (e.g., `analytics:read`, `bookings:write`). The server enforces scope-based access control per tool, logs every call to an audit table, and requires explicit `confirm: true` on destructive write operations. This is NOT the public MCP server (`linktime-mcp` npm package). This is an internal system used by LinkTime's agent infrastructure. ## Architecture ### Authentication Flow 1. Agent sends `POST /api/admin/agent-mcp` with `Authorization: Bearer lt_agent_{name}_{64hex}` 2. Server validates key format (cheap, no DB hit) 3. Server hashes key with SHA-256, looks up hash in `AgentApiKey` table 4. If valid and active: creates `McpHandler` with the agent's scopes 5. Handler processes JSON-RPC request, checking tool scope before execution 6. Every tool call is logged to `AgentToolCall` table (agent, tool, latency, status) ### Agent API Key Format - Pattern: `lt_agent_{agentName}_{64hexChars}` - Example: `lt_agent_support_a1b2c3d4e5f6...` (64 hex characters) - Only the SHA-256 hash is stored in the database - Raw key is shown once at creation, never again - Keys can be deactivated (`isActive: false`) or expired (`expiresAt`) ### Scope Model - Format: `{domain}:{action}` — e.g., `analytics:read`, `bookings:write` - **Write implies read**: An agent with `flags:write` automatically gets `flags:read` - Each tool requires exactly one scope - Agents are granted specific scopes at key creation ### JSON-RPC Methods | Method | Purpose | |--------|---------| | `initialize` | MCP handshake — returns protocol version and server info | | `ping` | Health check | | `tools/list` | Returns tools the agent has access to (filtered by scopes) | | `tools/call` | Execute a tool with arguments (scope check + audit log) | ### Response Format All tools return `McpToolResult`: ```json { "success": true, "data": { ... }, "message": "Human-readable result description", "pagination": { "page": 1, "limit": 20, "total": 150, "hasMore": true } } ``` Error responses: ```json { "success": false, "error": "Description of what went wrong" } ``` ### Safety Gates - **Scope enforcement**: Agent can only call tools matching its scopes - **`confirm: true`**: All destructive write tools require explicit `confirm: true` parameter - **Field whitelists**: Write tools only accept specific fields (e.g., `update_user_settings` only allows timezone, dateFormat, timeFormat) - **Audit trail**: Every tool call logged with agent identity, tool name, input hash, status code, latency - **Rate limits**: Built into the agent key system (not per-tool) --- ## Agent Personas These are the predefined agent roles and their scope assignments: ### Data Agent **Scopes:** `analytics:read`, `users:read`, `bookings:read`, `events:read`, `audit:read` **Tools accessible:** 20 **Purpose:** Daily brief generation, aggregate metrics, usage pattern analysis ### DevOps Agent **Scopes:** `analytics:read`, `infra:read`, `infra:write`, `flags:read`, `flags:write` **Tools accessible:** 18 **Purpose:** System monitoring, health checks, feature flag management ### Support Agent (base) **Scopes:** `users:read`, `bookings:read`, `contacts:read`, `contacts:write`, `events:read`, `audit:read`, `analytics:read` **Tools accessible:** 25 **Purpose:** Customer ticket handling, user lookup, contact corrections ### Support Agent (elevated) **Scopes:** All base support scopes + `bookings:write` **Tools accessible:** 27 **Purpose:** Booking cancel/reschedule — granted per-case by Orchestrator **Why separate:** Support processes customer emails (prompt injection vector). Base key cannot mutate bookings. ### Orchestrator Agent **Scopes:** `analytics:read`, `users:read`, `users:write`, `flags:read`, `flags:write`, `audit:read` **Tools accessible:** 18 **Purpose:** Cross-agent coordination, user tagging, feature flag control ### Retention Agent **Scopes:** `users:read`, `bookings:read`, `contacts:read`, `analytics:read`, `events:read` **Tools accessible:** 20 **Purpose:** Churn prevention, engagement analysis, at-risk user identification ### CTO Agent **Scopes:** `analytics:read`, `infra:read`, `flags:read`, `codebase:read`, `budget:read` **Tools accessible:** 22 **Purpose:** Architecture review, GitHub codebase inspection, system monitoring ### SEO Agent **Scopes:** `analytics:read`, `users:read`, `email:write` **Tools accessible:** 14 **Purpose:** Search optimization, traffic analysis, internal reporting ### Growth Agent **Scopes:** `analytics:read`, `users:read`, `email:write` **Tools accessible:** 14 **Purpose:** Growth experiments, A/B testing analysis, marketing emails ### Outbound Agent **Scopes:** `analytics:read`, `users:read`, `contacts:read`, `email:write` **Tools accessible:** 16 **Purpose:** Outreach, lead nurturing, follow-up emails ### Content Agent **Scopes:** `analytics:read`, `email:write`, `images:write` **Tools accessible:** 12 **Purpose:** Content creation, image generation, internal newsletters --- ## Tool Reference — Analytics Domain (9 tools) Scope: `analytics:read` ### get_dashboard Get the main KPI dashboard: DAU/WAU/MAU, user growth, conversion funnel, booking funnel, revenue by currency, email health, webhook health, estimated costs, and auto-generated insights. **Input:** - `preset` (string, optional): Date range — `"7d"`, `"30d"`, or `"90d"`. Default: `"30d"` **Returns:** Active users (DAU/WAU/MAU), user growth with percent change, conversion funnel (signup → profile → event → booking), booking funnel (confirmed/cancelled/rescheduled), revenue per currency, email delivery rate, webhook success rate, estimated monthly cost, and auto-generated insights array. ### get_revenue_metrics Get detailed revenue metrics: revenue per currency (never cross-currency sums), booking counts (paid vs free), top 10 earners per currency, and period-over-period percent change. **Input:** - `preset` (string, optional): `"7d"` | `"30d"` | `"90d"`. Default: `"30d"` **Returns:** Revenue breakdown by currency, paid/free booking counts, top earners per currency, percent changes vs previous period. ### get_user_metrics Get detailed user analytics: active users (DAU/WAU/MAU), growth rate, churn analysis (30d/90d inactive segments), conversion funnel, integration adoption rates, and top users by bookings. **Input:** - `preset` (string, optional): `"7d"` | `"30d"` | `"90d"`. Default: `"30d"` **Returns:** Active user counts, growth numbers with percent change, conversion funnel (signup → first event → first booking), growth trend (daily data points), top 10 users by bookings, integration adoption rates (Google Calendar, Outlook, HubSpot, etc.), churn analysis (never created event, created event but no bookings, inactive 30+ days, inactive 90+ days). ### get_cost_metrics Get cost breakdown: variable costs (email at $0.001/email, Stripe 2.9%+$0.30, PayPal fees), fixed infrastructure costs (Railway, domain, Clerk), and projected monthly total. **Input:** - `preset` (string, optional): `"7d"` | `"30d"` | `"90d"`. Default: `"30d"` **Returns:** Variable costs breakdown, fixed infrastructure costs, totals (variable, fixed, grand total), projected monthly estimate. ### get_traffic_metrics Get website traffic analytics: page views, unique visitors, visitor DAU/WAU/MAU, landing→signup conversion rate, daily trend, top pages, top referrers, top countries, and visitor conversion funnel. **Input:** - `preset` (string, optional): `"7d"` | `"30d"` | `"90d"`. Default: `"30d"` **Returns:** Total views, unique visitors, DAU/WAU/MAU, conversion rate, daily trend data points, top 10 pages, top referrers, top countries, visitor conversion funnel, total row count. ### get_email_metrics Get email delivery health: total emails sent, delivery success rate, breakdown by email type, top failure reasons, and period-over-period percent changes. **Input:** - `preset` (string, optional): `"7d"` | `"30d"` | `"90d"`. Default: `"30d"` **Returns:** Current period stats (total sent, success rate, breakdown by type, failure reasons), previous period comparison, percent changes. ### get_webhook_metrics Get webhook delivery health: active webhook count, total deliveries, success rate, breakdown by event type, recent failures with URLs and error details, and period-over-period percent changes. **Input:** - `preset` (string, optional): `"7d"` | `"30d"` | `"90d"`. Default: `"30d"` **Returns:** Active webhooks, total deliveries, success rate, event type breakdown, recent failures (URL, error, timestamp), percent changes. ### get_booking_metrics Get detailed booking analytics: total volume, cancellation rate, average bookings per user, busiest hours (UTC) and days of week, and event type popularity ranking. **Input:** - `preset` (string, optional): `"7d"` | `"30d"` | `"90d"`. Default: `"30d"` **Returns:** Total bookings, cancellation rate, bookings per user average, busiest hours (UTC distribution), busiest days, event type popularity. ### get_signup_funnel Get the signup conversion funnel for users who signed up in the given period: signup → created first event type → received first booking → received a paid booking. Includes drop-off percentages at each stage. **Input:** - `preset` (string, optional): `"7d"` | `"30d"` | `"90d"`. Default: `"30d"` **Returns:** Funnel stages with counts and drop-off percentages. --- ## Tool Reference — Feature Flags Domain (6 tools) ### list_flags **Scope:** `flags:read` List all feature flags with their global enabled/disabled status and the number of per-user overrides. **Input:** None **Returns:** Array of flags (id, key, name, description, isEnabled, overrideCount, createdAt). ### get_flag **Scope:** `flags:read` Get a single feature flag by ID with all its per-user overrides. **Input:** - `flagId` (string, required): Feature flag ID **Returns:** Flag object with overrides array. ### check_flag_for_user **Scope:** `flags:read` Check the resolved value of a feature flag for a specific user. Considers per-user overrides first, then global state. Returns false if flag doesn't exist. **Input:** - `flagKey` (string, required): Feature flag key (e.g., `"beta-features"`) - `userEmail` (string, optional): User email to check **Returns:** `{ flagKey, userEmail, isEnabled }`. ### toggle_flag **Scope:** `flags:write` Toggle a feature flag globally on or off. Does NOT affect per-user overrides. **Input:** - `flagId` (string, required): Feature flag ID - `isEnabled` (boolean, required): New global state **Returns:** Updated flag object. ### set_flag_override **Scope:** `flags:write` Set a per-user override for a feature flag. Overrides the global state for the specified user. Updates existing override if one exists. **Input:** - `flagId` (string, required): Feature flag ID - `email` (string, required): User email - `isEnabled` (boolean, required): Override value **Returns:** Override object. ### remove_flag_override **Scope:** `flags:write` Remove a per-user override. After removal, the user sees the global flag state. **Input:** - `flagId` (string, required): Feature flag ID - `email` (string, required): User email **Returns:** Success message. --- ## Tool Reference — Infrastructure Domain (4 tools) ### get_cron_health **Scope:** `infra:read` Get the status of all 12 cron jobs. Returns each job's name, endpoint path, HTTP method, and schedule. **Input:** None **Returns:** Array of 12 cron job definitions (name, path, method, schedule). ### get_system_test_results **Scope:** `infra:read` Run all system health tests. Tests 6 categories: Database (connection + 14 tables), OAuth Integrations, Environment Variables, External Services (10 APIs), Cron Jobs (12 endpoint reachability), and API Health. **Input:** None **Returns:** Test results per category with pass/fail/skip and duration. ### run_system_tests **Scope:** `infra:write` Identical to `get_system_test_results` but requires `infra:write` scope. Signals intent to take action based on results. **Input:** None **Returns:** Same as `get_system_test_results`. ### messaging_kill_switch **Scope:** `infra:write` Global enable/disable for ALL messaging agents. HIGH-IMPACT action — requires `confirm: true`. **Input:** - `action` (string, required): `"enable"` or `"disable"` - `confirm` (boolean, required): Must be `true` **Returns:** Action taken, number of agents affected. Creates audit log entry. --- ## Tool Reference — Audit Domain (1 tool) ### list_audit_logs **Scope:** `audit:read` Search and list audit log entries across all users. Filter by userId, action type, or date range. Paginated. **Input:** - `userId` (string, optional): Filter by user ID - `action` (string, optional): Filter by action (e.g., `"booking.created"`, `"settings.updated"`) - `from` (string, optional): Start date (ISO 8601) - `to` (string, optional): End date (ISO 8601) - `page` (number, optional): Page number. Default: 1 - `limit` (number, optional): Max 100. Default: 50 **Returns:** Paginated audit log entries with user info. Actions include: `auth.login`, `booking.created`, `booking.cancelled`, `booking.rescheduled`, `event_type.created`, `event_type.updated`, `event_type.deleted`, `settings.updated`, `integration.connected`, `integration.disconnected`, `payment.received`, `payment.refunded`. --- ## Tool Reference — Users Domain (7 tools) ### list_users **Scope:** `users:read` List all LinkTime users with pagination. Filter by search term (name/email/username), plan, activity status. Sort by createdAt, lastLoginAt, or bookingCount. **Input:** - `search` (string, optional): Search name, email, or username - `plan` (string, optional): `"FREE"` | `"PRO"` | `"BUSINESS"` - `status` (string, optional): `"active"` (booked in last 30d) | `"inactive"` - `sortBy` (string, optional): `"createdAt"` | `"lastLoginAt"` | `"bookingCount"`. Default: `"createdAt"` - `page` (number, optional): Default: 1 - `limit` (number, optional): Max 100. Default: 20 **Returns:** Paginated user list with id, email, name, username, plan, effectivePlan, createdAt, lastLoginAt, bookingCount, eventTypeCount. ### get_user **Scope:** `users:read` Get a single user's full profile including integration status (which calendars/CRMs are connected), plan details, and usage stats. **Input:** - `userId` (string, required): User ID **Returns:** Full user profile with: integration status (Google Calendar, Outlook, HubSpot, Attio, Salesforce — derived from presence of token fields), usage stats (total bookings, contacts, event types, SMS sent, voice credits). ### get_user_activity **Scope:** `users:read` Get a user's recent activity: last N bookings (with guest info), last N audit log entries, and recent email deliveries. **Input:** - `userId` (string, required): User ID - `limit` (number, optional): Items per category. Default: 10, max: 50 **Returns:** Recent bookings with guest info, recent audit log entries, recent email deliveries. ### search_users_by_email **Scope:** `users:read` Search for users by email address (case-insensitive partial match). Returns up to 10 matches. **This is the Support agent's primary entry point** — inbound tickets arrive as emails, so this is typically the first tool called. **Input:** - `email` (string, required): Email or partial email to search **Returns:** Array of matching users (up to 10) with basic info. ### update_user_plan **Scope:** `users:write` Change a user's subscription plan. **HIGH-IMPACT** — only Orchestrator should use this. Requires `confirm: true`. Updates the plan field only — does NOT modify Stripe subscriptions. **Input:** - `userId` (string, required): User ID - `plan` (string, required): `"FREE"` | `"PRO"` | `"BUSINESS"` - `confirm` (boolean, required): Must be `true` **Returns:** `{ userId, oldPlan, newPlan }`. Creates audit log entry. ### update_user_settings **Scope:** `users:write` Update a user's settings. Only whitelisted fields: timezone, dateFormat, timeFormat. Other fields silently ignored. **Input:** - `userId` (string, required): User ID - `settings` (object): `{ timezone?, dateFormat?, timeFormat? }` **Returns:** `{ userId, updatedFields }`. Creates audit log entry. ### disable_user **Scope:** `users:write` Disable a user account by setting `deletionRequestedAt`. **HIGH-IMPACT** — only Orchestrator should use this. Requires `confirm: true` and a reason. Flags for GDPR deletion pipeline (30 days). **Input:** - `userId` (string, required): User ID - `reason` (string, required): Reason for disabling - `confirm` (boolean, required): Must be `true` **Returns:** `{ userId, deletionRequestedAt, deletionScheduledFor }`. Creates audit log entry. --- ## Tool Reference — Bookings Domain (4 tools) ### list_all_bookings **Scope:** `bookings:read` List bookings across all users with filters. Returns paginated results with event type, host, and contact info. **Input:** - `userId` (string, optional): Filter by host user ID - `guestEmail` (string, optional): Filter by guest email (partial match) - `status` (string, optional): `"CONFIRMED"` | `"CANCELLED"` | `"RESCHEDULED"` - `from` (string, optional): Start date (ISO 8601) - `to` (string, optional): End date (ISO 8601) - `page` (number, optional): Default: 1 - `limit` (number, optional): Max 100. Default: 20 **Returns:** Paginated bookings with event type name, host info, contact info, status, meeting link. ### get_booking_detail **Scope:** `bookings:read` Get full details of a single booking: all fields, event type config, host info, contact info, email delivery logs, and SMS logs. **Input:** - `bookingId` (string, required): Booking ID **Returns:** Complete booking with event type, user, contact, email logs, SMS logs. ### cancel_booking_admin **Scope:** `bookings:write` Cancel a booking as admin. Fires all 7 side-effect chains: calendar sync (Google/Outlook/CalDAV), CRM updates (HubSpot/Attio/Salesforce), cancellation email to guest, webhooks, workflow triggers, in-app notification, and audit log. **Requires `confirm: true`.** Only accessible with `support-elevated` key. **Input:** - `bookingId` (string, required): Booking ID - `reason` (string, required): Cancellation reason - `notifyGuest` (boolean, optional): Send email to guest. Default: `true` - `confirm` (boolean, required): Must be `true` **Returns:** Cancellation result. Creates audit log entry. ### reschedule_booking_admin **Scope:** `bookings:write` Reschedule a booking as admin. Validates slot availability using the same algorithm as the public booking page, then fires all 7 side-effect chains. **Requires `confirm: true`.** Only accessible with `support-elevated` key. **Input:** - `bookingId` (string, required): Booking ID - `newStartTime` (string, required): New start time (ISO 8601) - `reason` (string, optional): Reschedule reason - `notifyGuest` (boolean, optional): Send email to guest. Default: `true` - `confirm` (boolean, required): Must be `true` **Returns:** Reschedule result with new booking times. Creates audit log entry. --- ## Tool Reference — Contacts Domain (3 tools) ### list_all_contacts **Scope:** `contacts:read` List contacts across all users with search and pagination. Filter by search term (name/email) or by userId (owner). **Input:** - `search` (string, optional): Search by name or email - `userId` (string, optional): Filter by owner user ID - `page` (number, optional): Default: 1 - `limit` (number, optional): Max 100. Default: 20 **Returns:** Paginated contacts with id, userId, name, email, phone, company, meetingCount, createdAt, updatedAt. ### get_contact_detail **Scope:** `contacts:read` Get full contact details including upcoming and past meetings, and owner user info. **Input:** - `contactId` (string, required): Contact ID **Returns:** Contact with name, email, phone, company, notes, owner user info, upcoming meetings (confirmed, future), past meetings (completed or cancelled). ### update_contact_admin **Scope:** `contacts:write` Update a contact's metadata. Only whitelisted fields: name, email, phone, company, notes (max 5000 chars). Other fields silently ignored. Used by Support agent after support interactions. **Input:** - `contactId` (string, required): Contact ID - `fields` (object, required): `{ name?, email?, phone?, company?, notes? }` **Returns:** Updated contact object. Creates audit log entry. --- ## Tool Reference — Events Domain (3 tools) ### list_all_event_types **Scope:** `events:read` List event types across all users with pagination. Filter by userId or active status. Returns event config and booking count. **Input:** - `userId` (string, optional): Filter by owner user ID - `isActive` (boolean, optional): Filter by active status - `page` (number, optional): Default: 1 - `limit` (number, optional): Max 100. Default: 20 **Returns:** Paginated event types with id, name, slug, description, durationMinutes, locationType, location, isActive, isPaid, price, currency, isGroupEvent, maxAttendees, bookingCount, owner info. ### get_event_type_detail **Scope:** `events:read` Get full details of a single event type including owner, booking count, and all configuration. **Input:** - `eventTypeId` (string, required): Event type ID **Returns:** Complete event type with all fields (duration, buffer times, location, payment, reminders, recurrence, group settings), owner user, booking count. ### check_user_availability **Scope:** `events:read` Check available booking slots for any user's event type. Uses the same availability algorithm as the public booking page. Returns slots for a date range (default: next 7 days). **Input:** - `userId` (string, required): User ID (event type owner) - `eventTypeSlug` (string, required): Event type slug (e.g., `"30min"`) - `timezone` (string, optional): IANA timezone. Default: `"UTC"` - `startDate` (string, optional): ISO 8601. Default: today - `endDate` (string, optional): ISO 8601. Default: startDate + 7 days **Returns:** `{ userId, eventTypeSlug, timezone, dateRange, slotCount, slots }`. Each slot has a start and end time in the requested timezone. --- ## Tool Reference — Budget Domain (2 tools) ### check_budget **Scope:** `budget:read` Check the calling agent's remaining daily budget. Returns whether the agent is allowed to proceed with spending actions, remaining budget amount, and warning if approaching limit. **Input:** - `agentName` (string, required): Agent identifier (e.g., `"support"`, `"cto"`) **Returns:** `{ allowed, remaining, limit, spent, warningThreshold }`. Warning threshold fires at 80% spent. ### check_global_budget **Scope:** `budget:read` Get cross-agent budget overview. Shows total spend across all agents, per-agent breakdown, and global cap status. **Input:** None **Returns:** `{ globalLimit, globalSpent, globalRemaining, agents: [{ name, spent, limit, remaining }] }`. **Budget limits:** - Support agent: $0.20/day (high volume, low cost per call) - All other agents: $5.00/day - Global cap: $50/day across all agents - Budget resets at midnight UTC --- ## Tool Reference — Codebase Domain (4 tools) Scope: `codebase:read` GitHub-backed tools for CTO and DevOps agents to inspect the LinkTime repository. ### search_codebase Search files in the repository by pattern. Uses GitHub Search API. **Input:** - `query` (string, required): Search query (filename, content, or pattern) - `path` (string, optional): Limit search to a directory path **Returns:** Array of matching files with path, name, and relevant content snippets. ### read_file Read the contents of a file from the repository. **Input:** - `path` (string, required): File path relative to repo root (e.g., `"src/lib/mcp/tools.ts"`) **Returns:** File contents as text. Returns error for binary files. ### list_directory List contents of a directory in the repository. **Input:** - `path` (string, optional): Directory path. Default: repo root **Returns:** Array of entries with name, type (`"file"` or `"dir"`), and size. ### list_recent_commits Show recent git commit history. **Input:** - `limit` (number, optional): Number of commits. Default: 10, max: 50 - `path` (string, optional): Filter to commits affecting this path **Returns:** Array of commits with SHA, message, author, date. **Note:** Uses GitHub REST API v3. With `GITHUB_TOKEN` set: 5,000 req/hr. Without: 60 req/hr (unauthenticated). --- ## Tool Reference — Email Domain (1 tool) ### send_email **Scope:** `email:write` Send a branded email via Resend. Each agent has category restrictions and rate limits. **Input:** - `to` (string, required): Recipient email address - `subject` (string, required): Email subject line - `body` (string, required): Email body (plain text or HTML) - `category` (string, required): `"support"` | `"transactional"` | `"marketing"` | `"internal"` **Returns:** `{ messageId, status }`. Creates `AgentEmailLog` entry. **Category permissions (per-agent):** | Agent | Allowed Categories | |-------|-------------------| | Support | support, transactional, internal | | CTO, DevOps | transactional, internal | | Orchestrator | support, transactional, internal | | Data, SEO | internal | | Growth, Outbound, CS, Content | marketing, internal | **Rate limits [daily, hourly]:** - Level 1 (Support, DevOps, Outbound, Orchestrator): [20, 5] - Level 0 (CTO, Data, SEO, Growth, CS, Content): [5, 2] **Marketing emails:** CAN-SPAM compliant with RFC 8058 one-click unsubscribe headers. Opt-out enforcement for marketing category. --- ## Tool Reference — Images Domain (1 tool) ### generate_image **Scope:** `images:write` Generate images via Scenario API using Gemini 3.1 model. **Input:** - `prompt` (string, required): Image generation prompt - `aspectRatio` (string, optional): One of 11 aspect ratios (e.g., `"1:1"`, `"16:9"`, `"9:16"`) - `resolution` (string, optional): `"512"` | `"1024"` | `"2048"` | `"4096"`. Default: `"1024"` - `numOutputs` (number, optional): 1-4 images. Default: 1 - `seed` (number, optional): Random seed for reproducibility - `useGoogleSearch` (boolean, optional): Enable Google Search grounding **Returns:** Array of generated image URLs with metadata. **Rate limit:** 50 generations/day per agent. --- ## Autonomy Framework Agent actions are classified into three tiers by reversibility: ### T1 — Fully Autonomous Read-only actions. No human approval needed. - Reading analytics, listing users/bookings/contacts, checking flags, searching codebase, budget checks ### T2 — Supervised Reversible writes. Require `confirm: true`. - Toggling feature flags, updating user settings, updating contacts, sending emails, generating images ### T3 — Human-in-the-Loop Irreversible or high-impact. Orchestrator or human approval required. - Cancelling bookings, changing user plans, disabling accounts, messaging kill switch ### Autonomy Levels - **L0**: Agent connected but read-only / internal-only email (SEO, Growth, Outbound, Customer Success, Content) - **L1**: Agent operates autonomously within scope with budget constraints (Support, CTO, Data, DevOps, Orchestrator) --- ## Scope Reference | Scope | Domain | Tools | Type | |-------|--------|-------|------| | `analytics:read` | Analytics | 9 | Read | | `flags:read` | Feature Flags | 3 | Read | | `flags:write` | Feature Flags | 3 | Write | | `infra:read` | Infrastructure | 2 | Read | | `infra:write` | Infrastructure | 2 | Write | | `audit:read` | Audit | 1 | Read | | `users:read` | Users | 4 | Read | | `users:write` | Users | 3 | Write | | `bookings:read` | Bookings | 2 | Read | | `bookings:write` | Bookings | 2 | Write | | `contacts:read` | Contacts | 2 | Read | | `contacts:write` | Contacts | 1 | Write | | `events:read` | Events | 3 | Read | | `budget:read` | Budget | 2 | Read | | `codebase:read` | Codebase | 4 | Read | | `email:write` | Email | 1 | Write | | `images:write` | Images | 1 | Write | **Total: 45 tools (29 read, 16 write) across 12 domains and 17 scopes.** --- ## Example: Calling a Tool ``` POST /api/admin/agent-mcp Authorization: Bearer lt_agent_support_a1b2c3d4... { "jsonrpc": "2.0", "id": "req-1", "method": "tools/call", "params": { "name": "search_users_by_email", "arguments": { "email": "john@example.com" } } } ``` Response: ```json { "jsonrpc": "2.0", "id": "req-1", "result": { "content": [{ "type": "text", "text": "{\"success\":true,\"data\":{\"users\":[{\"id\":\"clx...\",\"email\":\"john@example.com\",\"name\":\"John Doe\",\"plan\":\"PRO\"}],\"count\":1}}" }] } } ``` ## Example: Listing Available Tools ``` POST /api/admin/agent-mcp Authorization: Bearer lt_agent_support_a1b2c3d4... { "jsonrpc": "2.0", "id": "req-2", "method": "tools/list", "params": {} } ``` Returns only the tools the authenticated agent has access to (filtered by scopes). --- ## Key Files | File | Purpose | |------|---------| | `src/lib/mcp/types.ts` | McpTool, McpToolResult, JsonRpc types | | `src/lib/mcp/registry.ts` | ToolRegistry class (register, scope filter, access check) | | `src/lib/mcp/handler.ts` | JSON-RPC method routing, scope enforcement, audit logging | | `src/lib/mcp/tools.ts` | Global registry initialization (imports all 12 domain files) | | `src/lib/mcp/tools/analytics.ts` | 9 analytics tools | | `src/lib/mcp/tools/flags.ts` | 6 feature flag tools | | `src/lib/mcp/tools/infra.ts` | 4 infrastructure tools | | `src/lib/mcp/tools/audit.ts` | 1 audit log tool | | `src/lib/mcp/tools/users.ts` | 7 user tools (4 read + 3 write) | | `src/lib/mcp/tools/bookings.ts` | 4 booking tools (2 read + 2 write) | | `src/lib/mcp/tools/contacts.ts` | 3 contact tools (2 read + 1 write) | | `src/lib/mcp/tools/events.ts` | 3 event tools (all read) | | `src/lib/mcp/tools/budget.ts` | 2 budget tools (Cap Gate pattern) | | `src/lib/mcp/tools/codebase.ts` | 4 codebase tools (GitHub API) | | `src/lib/mcp/tools/email.ts` | 1 email tool (Resend, per-agent permissions) | | `src/lib/mcp/tools/images.ts` | 1 image generation tool (Scenario API) | | `src/lib/scenario.ts` | Scenario API client (Gemini 3.1) | | `src/lib/admin-users.ts` | User service layer (listUsers, getUser, getUserActivity, searchUsersByEmail) | | `src/lib/admin-bookings.ts` | Booking service layer (listBookings, getBookingDetail, cancelBooking, rescheduleBooking) | | `src/lib/agent-keys.ts` | Agent key generation, format validation, display formatting | | `src/lib/require-agent-key.ts` | Authentication middleware with scope checking | | `src/app/api/admin/agent-mcp/route.ts` | HTTP endpoint (POST handler) | | `src/lib/agent-events.ts` | Event bus for agent webhook delivery |