Files
PaperClipAI/server/src/routes/public-mcp.ts
T
DottaandPaperclip b8ffeb973a feat(runner): add experimental Grok Bot agent participation (#16219)
## Thinking Path

> - Paperclip manages AI agents that perform work for a company.
> - The shared Runner owns task admission, authority, receipts and
finalization.
> - An existing Grok Bot needs to receive assignments and return results
through that Runner.
> - The Bot also needs governed access when it starts work from its own
conversation.
> - This PR adds agent-purpose MCP access and routine webhook dispatch.
> - It reuses the external-agent Rust Runner and keeps Grok capabilities
explicit.
> - The provider stays experimental until the real-client managed
journeys pass.

## Linked Issues or Issue Description

**Agent or provider**
Grok Bot, distinct from the Grok Build coding runtime in #13882.

**Why this adapter is useful**
Users can assign work to an existing Bot, receive progress, questions,
documents and files in Paperclip, and let the Bot initiate work under
its agent permissions.

**How the agent is invoked**
A webhook-only routine delivers bounded references. Dedicated
named-agent OAuth and MCP provide inbound calls. Setup follows [Grok
routines](https://cursor.com/help/grok-bot/routines) and [custom
plugins](https://cursor.com/help/grok-bot/connect-plugins). The current
desktop app needs its Bot-generated Webhook URL navigation link when
routine-row clicks fail.

The GitHub search found related Grok Build runtime work, but no existing
Grok Bot agent provider. This extends the roadmap’s existing agent,
Runner, governance and artifact foundations.

## What Changed

- Add default-off Grok Bot participation through the shared real Rust
external backend, preserving native provider identity guarantees and
distinguishing session closure from remote termination.
- Bind agent OAuth to company, agent, client, gateway and authorizer;
recheck permissions and task-bound execution authority without
manufacturing a native identity.
- Persist routine configuration, dispatch intents, authenticated
acknowledgement and recovery holds. Store URL/key together in encrypted
secret storage, use guarded public egress, and never automatically
replay ambiguous HTTP delivery.
- Reuse native tools, durable waiting, completion assessment and review.
Add task-bound file grants through existing artifact storage; suppress
proactive echo dispatch and synchronous result wake loops.
- Enforce the current native deliverable work-mode policy at file-ticket
issuance and use. Add operator retries for confirmed rejected wakes,
with retained receipts, stable retry intent and current-authority
checks. Recovery locks bindings before routine rows. Thread Stop
resolves the selected run and its agent.
- Cancel queued and preparing Stop targets before assignment creation,
restore saved setup after a failed request and successful retry, and
publish the Grok provider descriptor schema. Advance the versioned
Copilot source declaration for the shared schema change; its
qualification remains pending.
- Filter task summaries with the shared privacy policy, preserve
feedback admission when wake delivery is blocked, reconcile settled
delivery receipts without restoring work authority, and bind every Stop
control to its displayed run. Recovery records distinguish dispatch
uncertainty from a revoked session.
- Add resumable guided setup, credential replacement, consent,
management, observed work status and stop/recovery controls, plus an
interactive Storybook journey using the production task thread, question
form and report card. Grok’s own apps remain available; Paperclip
workspace and third-party tools are deferred.

## Verification

- Five focused protocol, authorization, person MCP and Runner files: 192
tests pass. The Grok assigned-work case executes the actual Rust Runner,
saves a document, uploads/deduplicates a file and reaches ordinary
finalization.
- Proactive intake/deduplication and renewed-session recovery pass.
These use scripted clients and synthetic storage; they are not
real-provider acceptance.
- Repository typecheck, production build, token gates, map checks and
Storybook build/catalog checks pass. The local full-suite campaign was
stopped after macOS shared-memory exhaustion repeatedly prevented
embedded PostgreSQL startup. No local aggregate pass is claimed. The
first clean-worker CI run identified avatar fixture/configuration, flag
defaults, feature-card ordering and OpenAPI route-coverage gaps; all
four focused regressions pass after correction. Those regressions pass.
The latest clean-worker CI run also found a Copilot source-hash
declaration mismatch after the shared descriptor update; the corrected
declaration passes all 28 integrity tests. The next review corrections
pass 144 rendered UI tests, 21 OpenAPI tests and 82 Runner
contract/integrity/history tests. The latest database fixtures were
blocked at startup by host shared-memory exhaustion; clean-worker CI
must execute their new regressions. Full current-head CI now passes: 54
successful checks and four intentional skips. The database regression
uses the PostgreSQL driver result shape; file-policy, rejected-feedback
and lock-order cases pass on clean workers. Current-head Greptile is 5/5
with no unresolved findings.
- Rendered setup steps and outbound-only verification were walked
through in Storybook. Simulation cannot enable Done without an
authenticated-reply state.
- Actual client OAuth, continued access, reconnect and one routine wake
with an exact chat acknowledgement were observed separately. This
candidate’s live authenticated challenge, assigned/proactive workflows,
Linux managed artifact, restart and cleanup are not yet qualified. The
provider stays disabled by default.
- The separate Cloud ingress change forwards only exact task-bound
upload/download paths and preserves host identity and header stripping.
- Current Cloud policy reserves Test for pre-merge app/harness
experiments; Staging accepts only master-derived revisions. Real-client
qualification needs a supported, authorized deployment target and
remains outstanding.

## Risks

One append-only migration adds routine/dispatch state and extends shared
bindings and file tickets. The unshipped migrations were regenerated
after upstream consumed their original numbers. Rolling back code
retains the durable rows; revoke grants and inspect unknown remote
activity before resuming dispatch. Grok cannot confirm remote
termination, stream its complete transcript or report spending. Plugins
are account-wide and do not isolate credentials between Bots.
Real-client managed acceptance remains required before enabling the
experimental provider.

## Model Used

OpenAI Codex based on GPT-6, with reasoning, code execution and
browser/native UI tools. The exact deployment model ID and
context-window size are not exposed by this runtime.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-13 20:57:42 -05:00

263 lines
19 KiB
TypeScript

import express, { Router, type ErrorRequestHandler, type RequestHandler } from "express";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import { type PublicMcpEvents } from "../services/public-mcp/events.js";
import type { PublicMcpToolExtension } from "../services/public-mcp/dot-runner.js";
import { McpEventError } from "../services/public-mcp/event-webhooks.js";
import { DOT_RUNNER_MCP_PATH, DOT_RUNNER_MCP_SCOPES, PUBLIC_MCP_SCOPES, mcpConsentSchema, mcpInvitation, mcpSetupUrl } from "@paperclipai/shared";
import { renderMcpSetup, mcpSetupMarkdown } from "../services/public-mcp/setup.js";
import { DEVICE_GRANT, McpOAuthError, type PublicMcpOAuth } from "../services/public-mcp/oauth.js";
import { McpApiError, McpCapabilityError, publicMcpCapabilities, type createPublicMcpExecutor } from "../services/public-mcp/capabilities.js";
const oauthErrors: ErrorRequestHandler = (error, _req, res, next) => {
if (res.headersSent) { next(error); return; }
const known = error instanceof McpOAuthError;
res.status(known ? error.status : 500).json({
error: known ? error.code : "server_error",
error_description: known ? error.message : "Paperclip could not complete the connection request.",
});
};
/** Bounded in-process abuse guard; public deployments must also rate limit at their edge. */
function authRateLimit(): RequestHandler {
const windows = new Map<string, { count: number; until: number }>();
return (req, res, next) => {
const now = Date.now();
for (const [key, value] of windows) if (value.until <= now) windows.delete(key);
const key = req.ip ?? req.socket.remoteAddress ?? "unknown";
let entry = windows.get(key);
if (!entry) {
if (windows.size >= 10000) { res.status(429).json({ error: "temporarily_unavailable" }); return; }
entry = { count: 0, until: now + 60_000 }; windows.set(key, entry);
}
if (++entry.count > 60) { res.setHeader("Retry-After", "60"); res.status(429).json({ error: "temporarily_unavailable" }); return; }
next();
};
}
export function publicMcpIngressRoutes(oauth: PublicMcpOAuth, execute: ReturnType<typeof createPublicMcpExecutor>, events?: PublicMcpEvents, extension?: PublicMcpToolExtension) {
const router = Router();
const { origin, resource } = oauth.config;
const endpoint = new URL(resource).pathname;
const agentConnection = endpoint === DOT_RUNNER_MCP_PATH;
const oauthPath = agentConnection ? endpoint + "/oauth" : "/mcp/oauth";
const issuer = agentConnection ? origin + oauthPath : origin;
const scopes = agentConnection ? DOT_RUNNER_MCP_SCOPES : PUBLIC_MCP_SCOPES;
const metadataPath = "/.well-known/oauth-authorization-server" + (agentConnection ? oauthPath : "");
const prefix = origin + oauthPath;
const resourceMetadata = origin + "/.well-known/oauth-protected-resource" + endpoint;
if (!agentConnection) router.get(["/mcp/setup", "/mcp/setup.md"], async (req, res) => {
await oauth.assertEnabled();
const company = z.uuid().optional().safeParse(req.query.company);
if (!company.success) throw new McpOAuthError("invalid_request", "Invalid organization hint.");
res.setHeader("Cache-Control", "no-store");
res.setHeader("Referrer-Policy", "no-referrer");
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Content-Security-Policy", "default-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'");
res.vary("Accept");
if (req.path.endsWith(".md") || req.accepts(["html", "text/markdown"]) === "text/markdown") {
res.type("text/markdown").send(mcpSetupMarkdown(resource, company.data));
} else res.type("html").send(renderMcpSetup(resource, company.data));
});
router.use([oauthPath, endpoint], (_req, res, next) => {
res.setHeader("Cache-Control", "no-store");
res.setHeader("Referrer-Policy", "no-referrer");
next();
});
router.use(["/.well-known/oauth-protected-resource", metadataPath, endpoint, oauthPath + "/register", oauthPath + "/authorize", oauthPath + "/token"], async (_req, _res, next) => {
await oauth.assertEnabled();
next();
});
router.get(agentConnection ? ["/.well-known/oauth-protected-resource" + endpoint] : ["/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource" + endpoint], (_req, res) => res.json({
resource, authorization_servers: [issuer], scopes_supported: agentConnection ? DOT_RUNNER_MCP_SCOPES : ["paperclip:read", "paperclip:write", "paperclip:configure"], bearer_methods_supported: ["header"],
resource_name: agentConnection ? "Paperclip agent" : "Paperclip",
}));
router.get(metadataPath, (_req, res) => res.json({
issuer, authorization_endpoint: (oauth.config.authorizationOrigin ?? origin) + oauthPath + "/authorize", token_endpoint: prefix + "/token",
registration_endpoint: prefix + "/register", revocation_endpoint: prefix + "/revoke",
response_types_supported: ["code"], grant_types_supported: ["authorization_code", "refresh_token", DEVICE_GRANT],
device_authorization_endpoint: prefix + "/device_authorization",
token_endpoint_auth_methods_supported: ["none"], revocation_endpoint_auth_methods_supported: ["none"],
code_challenge_methods_supported: ["S256"], scopes_supported: scopes,
authorization_response_iss_parameter_supported: true,
client_id_metadata_document_supported: true,
}));
router.use(oauthPath, authRateLimit(), express.urlencoded({ extended: false, limit: "16kb" }));
router.post(oauthPath + "/register", async (req, res) => res.status(201).json(await oauth.register(req.body, req.ip ?? req.socket.remoteAddress ?? "unknown")));
router.post(oauthPath + "/device_authorization", async (req, res) => res.json(await oauth.deviceAuthorize(req.body, req.ip ?? req.socket.remoteAddress ?? "unknown")));
router.get(oauthPath + "/authorize", async (req, res) => res.redirect(303, await oauth.authorize(req.query, req.ip ?? req.socket.remoteAddress ?? "unknown")));
router.post(oauthPath + "/token", async (req, res) => res.json(await oauth.token(req.body ?? {})));
router.post(oauthPath + "/revoke", async (req, res) => {
if (typeof req.body?.token !== "string" || typeof req.body?.client_id !== "string") throw new McpOAuthError("invalid_request", "A token and client_id are required.");
await oauth.revokeToken(req.body.token, req.body.client_id); res.status(200).end();
});
router.all(endpoint, async (req, res) => {
if (req.headers.origin && req.headers.origin !== origin) { res.status(403).json({ error: "Invalid origin" }); return; }
const token = /^Bearer (\S+)$/i.exec(req.headers.authorization ?? "")?.[1];
let principal;
try { if (!token) throw new Error(); principal = await oauth.authenticate(token); }
catch {
res.setHeader("WWW-Authenticate", `Bearer resource_metadata="${resourceMetadata}", scope="${agentConnection ? "paperclip:agent" : "paperclip:read paperclip:write paperclip:configure"}", error="invalid_token"`);
res.status(401).json({ error: "invalid_token" }); return;
}
if (req.method !== "POST") { res.setHeader("Allow", "POST"); res.status(405).end(); return; }
const listTools = async () => ({
tools: [...(agentConnection ? [] : publicMcpCapabilities).map((c) => ({
name: c.name, description: c.description, inputSchema: z.toJSONSchema(c.schema) as { type: "object"; properties: Record<string, unknown> },
annotations: { readOnlyHint: !c.write && !c.configure, destructiveHint: !!c.destructive, idempotentHint: true, openWorldHint: !!c.write || !!c.configure },
})), ...await extension?.listTools(principal!) ?? []],
});
const callTool = async (request: z.infer<typeof CallToolRequestSchema>) => {
try {
const extensionTools = await extension?.listTools(principal!) ?? [];
const result = extensionTools.some(t => t.name === request.params.name)
? await extension!.callTool(principal!, request.params.name, request.params.arguments ?? {})
: agentConnection ? (() => { throw new McpOAuthError("access_denied", "This tool is unavailable on the agent connection."); })() : await execute(token!, request.params.name, request.params.arguments ?? {});
return { isError: result.outcome === "unknown" || result.outcome === "rejected", content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result };
} catch (error) {
if (error instanceof z.ZodError) {
const issues = error.issues.slice(0, 12).map(issue => ({
path: issue.path.slice(0, 8).filter(part => typeof part === "number" || (typeof part === "string" && /^[a-zA-Z][a-zA-Z0-9_]{0,80}$/.test(part))).join("."),
code: issue.code,
message: issue.code === "invalid_format" && issue.format === "uuid"
? "Use a valid UUID: 8-4-4-4-12 hex digits; the fourth group starts with 8, 9, a or b."
: issue.code === "unrecognized_keys" ? "Remove unsupported fields."
: "Check this field against the operation's input schema.",
}));
const result = { outcome: "rejected", phase: "validation", message: "Invalid tool arguments. No action was executed. Correct the indicated fields before trying again.", issues };
return { isError: true, content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result };
}
const message = error instanceof McpApiError || error instanceof McpCapabilityError || error instanceof McpOAuthError ? error.message
: "Paperclip could not confirm this operation. Before retrying a write, inspect the task and comments and keep the same requestId.";
return { isError: true, content: [{ type: "text", text: message }] };
}
};
const modern = req.headers["mcp-protocol-version"] === "2026-07-28"
|| req.body?.params?._meta?.["io.modelcontextprotocol/protocolVersion"] === "2026-07-28"
|| req.body?.method === "server/discover" || String(req.body?.method).startsWith("events/");
if (modern) {
const envelope = z.object({ jsonrpc: z.literal("2.0"), id: z.union([z.string(), z.number().int()]), method: z.string(), params: z.record(z.string(), z.unknown()) }).safeParse(req.body);
const fail = (code: number, message: string, data?: unknown) => res.status(code === -32601 ? 404 : code === -32603 ? 500 : 400)
.json({ jsonrpc: "2.0", id: envelope.success ? envelope.data.id : null, error: { code, message, ...(data ? { data } : {}) } });
if (!envelope.success) { fail(-32600, "Invalid MCP request."); return; }
const { method, params } = envelope.data;
const meta = params._meta as Record<string, unknown> | undefined;
if (!meta || typeof meta["io.modelcontextprotocol/protocolVersion"] !== "string"
|| !meta["io.modelcontextprotocol/clientCapabilities"] || typeof meta["io.modelcontextprotocol/clientCapabilities"] !== "object"
|| Array.isArray(meta["io.modelcontextprotocol/clientCapabilities"])) { fail(-32602, "Required per-request MCP metadata is missing."); return; }
const decodeHeader = (value: unknown) => typeof value === "string" && /^=\?base64\?.*\?=$/.test(value)
? Buffer.from(value.slice(9, -2), "base64").toString("utf8") : value;
if (req.headers["mcp-protocol-version"] !== meta["io.modelcontextprotocol/protocolVersion"] || req.headers["mcp-method"] !== method
|| (method === "tools/call" && decodeHeader(req.headers["mcp-name"]) !== params.name)) { fail(-32020, "MCP headers must match the request body."); return; }
if (meta["io.modelcontextprotocol/protocolVersion"] !== "2026-07-28") { fail(-32022, "Unsupported protocol version.", { supportedVersions: ["2026-07-28"] }); return; }
if (!req.is("application/json")) { fail(-32600, "Use application/json."); return; }
try {
let result: Record<string, unknown>;
switch (method) {
case "server/discover": result = { supportedVersions: ["2026-07-28"], capabilities: { tools: {}, ...(events ? { events: {} } : {}) } }; break;
case "tools/list": result = await listTools(); break;
case "tools/call": result = await callTool(CallToolRequestSchema.parse(envelope.data)); break;
case "events/list":
if (!events) { fail(-32601, "Events are unavailable."); return; }
if (params.cursor != null) { fail(-32602, "Invalid event catalog cursor."); return; }
result = { events: events.definitions }; break;
case "events/subscribe": {
if (!events) { fail(-32601, "Events are unavailable."); return; }
// The broker supplies its original access proof only for hosted subscriptions.
// It is validated against the fixed Cloud origin before being retained encrypted.
const authority = z.object({ token: z.string().max(24000), expiresAt: z.number() }).safeParse(meta["ai.paperclip/cloudAuthority"]);
result = await events.subscribe(principal!, params, authority.success ? authority.data : undefined); break;
}
case "events/unsubscribe":
if (!events) { fail(-32601, "Events are unavailable."); return; }
result = await events.unsubscribe(principal!, params); break;
default: fail(-32601, "Method not found."); return;
}
res.json({ jsonrpc: "2.0", id: envelope.data.id, result: { ...result, resultType: "complete", _meta: { "io.modelcontextprotocol/serverInfo": { name: "paperclip", version: "0.1.0" } } } });
} catch (error) {
if (error instanceof McpEventError) fail(error.code, error.message, error.reason ? { reason: error.reason } : undefined);
else if (error instanceof z.ZodError || error instanceof McpApiError || error instanceof McpOAuthError) fail(-32602, "Invalid arguments or unavailable authority.");
else fail(-32603, "Paperclip could not complete the request.");
}
return;
}
const server = new Server({ name: "paperclip", version: "0.1.0" }, { capabilities: { tools: {} } });
server.setRequestHandler(ListToolsRequestSchema, listTools);
server.setRequestHandler(CallToolRequestSchema, callTool);
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
res.on("close", () => { void transport.close(); void server.close(); });
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
});
router.use(oauthErrors);
return router;
}
export function publicMcpManagementRoutes(oauth: PublicMcpOAuth, agentOAuth?: PublicMcpOAuth) {
const router = Router();
const requestOAuth = async (id: string, dotOnly = false) => {
if (agentOAuth && await agentOAuth.ownsRequest(id)) return agentOAuth;
if (dotOnly) throw new McpOAuthError("invalid_request", "Dot connection request is expired or unavailable.", 404);
return oauth;
};
const deviceOAuth = async (code: string) => agentOAuth && await agentOAuth.ownsDevice(code) ? agentOAuth : oauth;
const realUser: RequestHandler = (req, _res, next) => {
if (req.actor.type !== "board" || !req.actor.userId || !["session", "cloud_tenant"].includes(req.actor.source ?? "")) {
throw new McpOAuthError("access_denied", "Sign in to manage assistant connections.", 401);
}
next();
};
const sameOrigin: RequestHandler = (req, _res, next) => {
const origin = req.headers.origin ?? (req.headers.referer ? new URL(req.headers.referer).origin : "");
if (origin !== oauth.config.origin && origin !== oauth.config.authorizationOrigin) throw new McpOAuthError("access_denied", "Connection changes require the Paperclip browser origin.", 403);
next();
};
router.use(["/mcp", "/dot-mcp"], (_req, res, next) => { res.setHeader("Cache-Control", "no-store"); next(); });
router.get("/mcp/device", authRateLimit(), async (req, res) => {
const code = z.string().regex(/^[A-Za-z0-9 -]{8,12}$/).safeParse(req.query.user_code);
if (!code.success) throw new McpOAuthError("invalid_request", "Enter the code shown by your assistant.");
res.json(await (await deviceOAuth(code.data)).describeDevice(code.data, req.actor));
});
router.post("/mcp/device/consent", realUser, sameOrigin, authRateLimit(), async (req, res) => {
const parsed = mcpConsentSchema.extend({ userCode: z.string().regex(/^[A-Za-z0-9 -]{8,12}$/) }).safeParse(req.body);
if (!parsed.success) throw new McpOAuthError("invalid_request", "Enter your code and choose the requested access.");
res.json(await (await deviceOAuth(parsed.data.userCode)).consentDevice(parsed.data.userCode, req.actor, parsed.data));
});
router.get(["/mcp/requests/:id", "/dot-mcp/requests/:id"], async (req, res) => {
let setupUrl: string | null = null;
if (process.env.PAPERCLIP_CLOUD_API_ORIGIN) {
const base = new URL(process.env.PAPERCLIP_CLOUD_API_ORIGIN);
if (base.protocol === "https:") setupUrl = new URL("/orgs/new", base).toString();
}
res.json(await (await requestOAuth(String(req.params.id), req.path.startsWith("/dot-mcp/"))).describeRequest(String(req.params.id), req.actor, setupUrl));
});
router.post(["/mcp/requests/:id/dot-pairing/preview", "/dot-mcp/requests/:id/dot-pairing/preview"], sameOrigin, authRateLimit(), async (req, res) => {
const parsed = z.object({ pairingCode: z.string().regex(/^[A-Za-z0-9_-]{32}$/) }).strict().safeParse(req.body);
if (!parsed.success) throw new McpOAuthError("invalid_request", "Enter the one-use code from the Dot setup prompt.");
res.json(await (await requestOAuth(String(req.params.id), req.path.startsWith("/dot-mcp/"))).describeDotPairing(String(req.params.id), parsed.data.pairingCode));
});
router.post(["/mcp/requests/:id/dot-pairing", "/dot-mcp/requests/:id/dot-pairing"], sameOrigin, authRateLimit(), async (req, res) => {
const parsed = z.object({ pairingCode: z.string().regex(/^[A-Za-z0-9_-]{32}$/) }).strict().safeParse(req.body);
if (!parsed.success) throw new McpOAuthError("invalid_request", "Enter the one-use code from the Dot setup prompt.");
res.json(await (await requestOAuth(String(req.params.id), req.path.startsWith("/dot-mcp/"))).consentDotPairing(String(req.params.id), parsed.data.pairingCode));
});
router.post("/mcp/requests/:id/consent", realUser, sameOrigin, async (req, res) => {
const parsed = mcpConsentSchema.safeParse(req.body);
if (!parsed.success) throw new McpOAuthError("invalid_request", "Choose a company and the requested access.");
res.json(await (await requestOAuth(String(req.params.id))).consent(String(req.params.id), req.actor, parsed.data));
});
router.get("/mcp/setup", realUser, async (_req, res) => res.json({
enabled: await oauth.isEnabled(), serverUrl: oauth.config.resource,
invitationUrl: mcpSetupUrl(oauth.config.resource), invitation: mcpInvitation(oauth.config.resource),
}));
router.get("/mcp/connections", realUser, async (req, res) => res.json(await oauth.listConnections(req.actor.userId!)));
router.delete("/mcp/connections/:id", realUser, sameOrigin, async (req, res) => {
if (!z.uuid().safeParse(req.params.id).success) throw new McpOAuthError("invalid_request", "Invalid connection ID.");
await oauth.revokeConnection(String(req.params.id), req.actor.userId!); res.status(204).end();
});
router.use(["/mcp", "/dot-mcp"], oauthErrors);
return router;
}