@catamorphic/fastify-plugin 0.1.0-alpha.39 → 0.1.0-alpha.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/NOTICE.txt +7 -0
  2. package/dist/app.d.ts +2 -0
  3. package/dist/app.d.ts.map +1 -1
  4. package/dist/chunk-jytcc42y.js +592 -0
  5. package/dist/chunk-jytcc42y.js.map +11 -0
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1673 -411
  9. package/dist/index.js.map +29 -25
  10. package/dist/mcp-scopes.d.ts +12 -0
  11. package/dist/mcp-scopes.d.ts.map +1 -0
  12. package/dist/mcp-server.d.ts +158 -0
  13. package/dist/mcp-server.d.ts.map +1 -0
  14. package/dist/mcp-shared.d.ts +3 -50
  15. package/dist/mcp-shared.d.ts.map +1 -1
  16. package/dist/mcp.d.ts +4 -2
  17. package/dist/mcp.d.ts.map +1 -1
  18. package/dist/mcp.js +6 -4
  19. package/dist/mcp.js.map +1 -1
  20. package/dist/plugin.d.ts +26 -2
  21. package/dist/plugin.d.ts.map +1 -1
  22. package/dist/project-capabilities.d.ts.map +1 -1
  23. package/dist/project-mcp-surface.d.ts +3 -4
  24. package/dist/project-mcp-surface.d.ts.map +1 -1
  25. package/dist/routes/agent.d.ts.map +1 -1
  26. package/dist/routes/apps-mcp.d.ts.map +1 -1
  27. package/dist/routes/client-runners.d.ts.map +1 -1
  28. package/dist/routes/connection-mcp.d.ts.map +1 -1
  29. package/dist/routes/documents.d.ts.map +1 -1
  30. package/dist/routes/environments.d.ts.map +1 -1
  31. package/dist/routes/project-mcp.d.ts.map +1 -1
  32. package/dist/routes/projects.d.ts.map +1 -1
  33. package/dist/routes/publications.d.ts.map +1 -1
  34. package/dist/routes/run-errors.d.ts.map +1 -1
  35. package/dist/routes/runs.d.ts.map +1 -1
  36. package/dist/routes/server-mcp.d.ts +17 -0
  37. package/dist/routes/server-mcp.d.ts.map +1 -0
  38. package/dist/routes/session-mailboxes.d.ts.map +1 -1
  39. package/dist/routes/triggers.d.ts.map +1 -1
  40. package/dist/routes/watchers.d.ts.map +1 -1
  41. package/dist/routes/workflow-enablements.d.ts.map +1 -1
  42. package/dist/routes/workflows.d.ts.map +1 -1
  43. package/dist/schemas.d.ts +3684 -28
  44. package/dist/schemas.d.ts.map +1 -1
  45. package/dist/session-mcp.d.ts +54 -0
  46. package/dist/session-mcp.d.ts.map +1 -0
  47. package/dist/session-tools.d.ts +49 -0
  48. package/dist/session-tools.d.ts.map +1 -0
  49. package/package.json +12 -12
  50. package/src/app.ts +3 -0
  51. package/src/index.ts +1 -0
  52. package/src/mcp-scopes.ts +69 -0
  53. package/src/mcp-server.ts +827 -0
  54. package/src/mcp-shared.ts +3 -151
  55. package/src/mcp.ts +6 -5
  56. package/src/plugin.ts +73 -2
  57. package/src/project-capabilities.ts +5 -3
  58. package/src/project-mcp-program.ts +2 -2
  59. package/src/project-mcp-surface.ts +18 -239
  60. package/src/routes/agent.ts +384 -41
  61. package/src/routes/apps-mcp.ts +84 -82
  62. package/src/routes/client-runners.ts +3 -1
  63. package/src/routes/connection-mcp.ts +6 -13
  64. package/src/routes/documents.ts +4 -0
  65. package/src/routes/environments.ts +49 -1
  66. package/src/routes/project-mcp.ts +176 -154
  67. package/src/routes/projects.ts +6 -0
  68. package/src/routes/publications.ts +2 -0
  69. package/src/routes/run-errors.ts +5 -1
  70. package/src/routes/runs.ts +4 -0
  71. package/src/routes/server-mcp.ts +151 -0
  72. package/src/routes/session-mailboxes.ts +1 -0
  73. package/src/routes/triggers.ts +6 -1
  74. package/src/routes/watchers.ts +1 -0
  75. package/src/routes/workflow-enablements.ts +132 -1
  76. package/src/routes/workflows.ts +4 -0
  77. package/src/schemas.ts +347 -5
  78. package/src/session-mcp.ts +696 -0
  79. package/src/session-tools.ts +169 -0
  80. package/dist/chunk-baagvvm3.js +0 -164
  81. package/dist/chunk-baagvvm3.js.map +0 -10
@@ -10,11 +10,10 @@ import type { FastifyInstance } from "fastify";
10
10
  import { z } from "zod";
11
11
  import type { RouteContext } from "../app.js";
12
12
  import { resolveIdentity } from "../http-identity.js";
13
+ import { mayCallTool, mcpStateSecret, withheldTools } from "../mcp-scopes.js";
14
+ import { type McpTool, serveMcp } from "../mcp-server.js";
13
15
  import {
14
16
  callPollRunTool,
15
- handleMcpPost,
16
- McpRequestError,
17
- negotiateProtocolVersion,
18
17
  POLL_RUN_TOOL,
19
18
  POLL_RUN_TOOL_DEFINITION,
20
19
  toolError,
@@ -24,17 +23,18 @@ import { programTools, projectInstructions } from "../project-mcp-program.js";
24
23
  import {
25
24
  allowedWorkflowNames,
26
25
  mayUseProject,
27
- type SurfaceTool,
28
26
  surfaceTools,
29
27
  } from "../project-mcp-surface.js";
28
+ import { sessionMcp } from "../session-mcp.js";
30
29
 
31
30
  /**
32
- * MCP server for a project (ADR 0042, ADR 0055): the single "bring your own
33
- * agent" door. Serves the project's AI-callable workflows — one tool per
34
- * trigger binding of every kind the host registered under `mcpToolKinds` —
35
- * beside the documents surface, skills and `ask_agent`
36
- * (`project-mcp-surface.ts`), everything narrowed to the caller's scope by
37
- * the core services themselves. Workflow tools:
31
+ * MCP server for a project (ADR 0042, ADR 0055): a project's own door for
32
+ * a member's agent. Serves the project's AI-callable workflows (one tool
33
+ * per trigger binding of every kind the host registered under
34
+ * `mcpToolKinds`) beside the documents surface, skills and the session
35
+ * operations (`project-mcp-surface.ts`), everything narrowed to the
36
+ * caller's scope by the core services themselves, and to the scopes of the
37
+ * caller's token (ADR 0347). Workflow tools:
38
38
  * the tool's input schema is the binding's frozen per-workflow schema (a
39
39
  * hole instantiated by the workflow's own input type), its metadata comes
40
40
  * from the binding's constant config, and calling it fires the trigger
@@ -44,8 +44,8 @@ import {
44
44
  *
45
45
  * Unlike `/apps-mcp` (which serves published apps and their UI resources),
46
46
  * this endpoint needs no app: binding a tool kind in workflow code is the
47
- * whole opt-in. Stateless Streamable-HTTP JSON-RPC, same era and identity
48
- * model as the rest of the plugin.
47
+ * whole opt-in. Stateless Streamable HTTP in both protocol eras
48
+ * (`mcp-server.ts`), with the identity model of the rest of the plugin.
49
49
  *
50
50
  * The workflow's output schema deliberately rides `_meta`, NOT the tool's
51
51
  * `outputSchema`: MCP clients validate `structuredContent` against an
@@ -83,160 +83,182 @@ export function registerProjectMcpRoutes(
83
83
  reply: import("fastify").FastifyReply,
84
84
  ) => reply.status(405).header("allow", "POST").send();
85
85
  app.get("/projects/:projectId/mcp", notAllowed);
86
- app.delete("/projects/:projectId/mcp", notAllowed);
86
+ app.delete(
87
+ "/projects/:projectId/mcp",
88
+ { config: { tokenScope: "work:read" } },
89
+ notAllowed,
90
+ );
87
91
 
88
- app.post("/projects/:projectId/mcp", async (request, reply) => {
89
- const core = ctx.core;
90
- if (!core) {
91
- return reply.status(503).send({ error: "Service not configured" });
92
- }
93
- if (!ctx.features.mcp) {
94
- return reply
95
- .status(404)
96
- .send({ error: "MCP is turned off on this server" });
97
- }
98
- const { projectId } = request.params as { projectId: string };
99
- const { sessionId, allocationId } = request.query as {
100
- sessionId?: string;
101
- allocationId?: string;
102
- };
103
- const identity = resolveIdentity(request);
104
- // Someone the project grants nothing sees no project here at all.
105
- if (!mayUseProject(identity, projectId)) {
106
- return reply.status(404).send({ error: "Project not found" });
107
- }
108
- const abort = new AbortController();
109
- reply.raw.once("close", () => abort.abort());
110
- const gatewayTools = sessionId
111
- ? agentCapabilityTools(
112
- core.agentCapabilities.forSession({
113
- identity,
114
- projectId,
115
- sessionId,
116
- allocationId,
92
+ app.post(
93
+ "/projects/:projectId/mcp",
94
+ { config: { tokenScope: "work:read" } },
95
+ async (request, reply) => {
96
+ const core = ctx.core;
97
+ if (!core) {
98
+ return reply.status(503).send({ error: "Service not configured" });
99
+ }
100
+ if (!ctx.features.mcp) {
101
+ return reply
102
+ .status(404)
103
+ .send({ error: "MCP is turned off on this server" });
104
+ }
105
+ const { projectId } = request.params as { projectId: string };
106
+ const { sessionId, allocationId } = request.query as {
107
+ sessionId?: string;
108
+ allocationId?: string;
109
+ };
110
+ const identity = resolveIdentity(request);
111
+ // Someone the project grants nothing sees no project here at all.
112
+ if (!mayUseProject(identity, projectId)) {
113
+ return reply.status(404).send({ error: "Project not found" });
114
+ }
115
+ const abort = new AbortController();
116
+ reply.raw.once("close", () => abort.abort());
117
+ const gatewayTools = sessionId
118
+ ? agentCapabilityTools(
119
+ core.agentCapabilities.forSession({
120
+ identity,
121
+ projectId,
122
+ sessionId,
123
+ allocationId,
124
+ }),
125
+ abort.signal,
126
+ )
127
+ : [];
128
+ // What the current protocol adds to the chat tools: tasks, questions
129
+ // asked of the client's person, and chats as resources (ADR 0347).
130
+ const chats = sessionMcp({
131
+ core,
132
+ identity,
133
+ projectId,
134
+ ...(sessionId ? { currentSessionId: sessionId } : {}),
135
+ stateSecret: mcpStateSecret(ctx),
136
+ });
137
+ const surface: McpTool[] = [
138
+ ...surfaceTools(core, identity, projectId, ctx.features, sessionId).map(
139
+ (tool) =>
140
+ chats?.tools.find(
141
+ (chat) => chat.definition.name === tool.definition.name,
142
+ ) ?? tool,
143
+ ),
144
+ ...programTools(core, identity, projectId),
145
+ ...(ctx.projectMcp?.tools?.({ identity, projectId }) ?? []).map(
146
+ (tool): McpTool => ({
147
+ definition: tool.definition,
148
+ call: async (args) => {
149
+ try {
150
+ return toolValue(await tool.call(args));
151
+ } catch (error) {
152
+ return toolError(
153
+ error instanceof Error ? error.message : String(error),
154
+ );
155
+ }
156
+ },
117
157
  }),
118
- abort.signal,
119
- )
120
- : [];
121
- const surface: SurfaceTool[] = [
122
- ...surfaceTools(core, identity, projectId, ctx.features, sessionId),
123
- ...programTools(core, identity, projectId),
124
- ...(ctx.projectMcp?.tools?.({ identity, projectId }) ?? []).map(
125
- (tool) => ({
126
- definition: tool.definition,
127
- call: async (args: Record<string, unknown>) => {
128
- try {
129
- return toolValue(await tool.call(args));
130
- } catch (error) {
131
- return toolError(
132
- error instanceof Error ? error.message : String(error),
133
- );
134
- }
135
- },
136
- }),
137
- ),
138
- ];
139
-
140
- return handleMcpPost(reply, request.body, async (method, params) => {
141
- switch (method) {
142
- case "initialize":
143
- return {
144
- protocolVersion: negotiateProtocolVersion(params.protocolVersion),
145
- capabilities: { tools: { listChanged: false } },
146
- serverInfo: {
147
- version: "1.0.0",
148
- ...(ctx.projectMcp?.serverInfo ?? {
149
- name: "catamorphic",
150
- title: "Catamorphic project",
158
+ ),
159
+ ];
160
+ /** Every tool the caller's roles reach, before its token narrows them. */
161
+ let roster: Promise<McpTool[]> | undefined;
162
+ const allTools = () => {
163
+ roster ??= (async () => {
164
+ const workflows = await loadProjectTools(core, identity, projectId);
165
+ // A workflow tool that claims a surface name wins the name (the
166
+ // project chose it); the surface tool steps aside for this project.
167
+ const taken = new Set(workflows.map((tool) => tool.name));
168
+ return [
169
+ ...gatewayTools.map(
170
+ (tool): McpTool => ({
171
+ definition: {
172
+ name: tool.name,
173
+ description: tool.description,
174
+ inputSchema: z.toJSONSchema(z.object(tool.parameters)),
175
+ },
176
+ call: async (input) => {
177
+ try {
178
+ return toolValue(
179
+ await tool.execute(input, {
180
+ projectId,
181
+ sessionId,
182
+ // An MCP call hears nothing of its turn: it waits
183
+ // while asked (ADR 0264).
184
+ stopWaiting: abort.signal,
185
+ }),
186
+ );
187
+ } catch (error) {
188
+ return toolError(
189
+ error instanceof Error
190
+ ? error.message
191
+ : "Capability failed",
192
+ );
193
+ }
194
+ },
151
195
  }),
152
- },
153
- instructions: await projectInstructions({
196
+ ),
197
+ ...workflows
198
+ .filter(
199
+ (tool) =>
200
+ !gatewayTools.some((gateway) => gateway.name === tool.name),
201
+ )
202
+ .map(
203
+ (tool): McpTool => ({
204
+ definition: toolDefinition(tool),
205
+ scope: "sessions:run",
206
+ call: (input) =>
207
+ callTool(core, identity, projectId, tool.name, input),
208
+ }),
209
+ ),
210
+ ...(workflows.length > 0 || core.mcpToolKinds.length > 0
211
+ ? [
212
+ {
213
+ definition: POLL_RUN_TOOL_DEFINITION,
214
+ call: (input: Record<string, unknown>) =>
215
+ callPollRunTool(core, identity, input),
216
+ },
217
+ ]
218
+ : []),
219
+ ...surface.filter(
220
+ (tool) => !taken.has(String(tool.definition.name)),
221
+ ),
222
+ ];
223
+ })();
224
+ return roster;
225
+ };
226
+ const tools = async () =>
227
+ (await allTools()).filter((tool) => mayCallTool(identity, tool));
228
+
229
+ return serveMcp({
230
+ request,
231
+ reply,
232
+ ...(ctx.mcp?.resourceMetadataUrl
233
+ ? { resourceMetadataUrl: ctx.mcp.resourceMetadataUrl }
234
+ : {}),
235
+ endpoint: {
236
+ serverInfo: {
237
+ version: "1.0.0",
238
+ ...(ctx.projectMcp?.serverInfo ?? {
239
+ name: "catamorphic",
240
+ title: "Catamorphic project",
241
+ }),
242
+ },
243
+ instructions: async () =>
244
+ projectInstructions({
154
245
  core,
155
246
  identity,
156
247
  projectId,
157
248
  toolNames: new Set(
158
- surface.map((tool) => String(tool.definition.name)),
249
+ (await tools()).map((tool) => String(tool.definition.name)),
159
250
  ),
160
251
  ...(ctx.projectMcp?.instructions
161
252
  ? { host: ctx.projectMcp.instructions }
162
253
  : {}),
163
254
  }),
164
- };
165
- case "ping":
166
- return {};
167
- case "tools/list": {
168
- const tools = await loadProjectTools(core, identity, projectId);
169
- // A workflow tool that claims a surface name wins the name (the
170
- // project chose it); the surface tool steps aside for this project.
171
- const taken = new Set(tools.map((tool) => tool.name));
172
- return {
173
- tools: [
174
- ...gatewayTools.map((tool) => ({
175
- name: tool.name,
176
- description: tool.description,
177
- inputSchema: z.toJSONSchema(z.object(tool.parameters)),
178
- })),
179
- ...tools
180
- .filter(
181
- (tool) =>
182
- !gatewayTools.some((gateway) => gateway.name === tool.name),
183
- )
184
- .map(toolDefinition),
185
- ...(tools.length > 0 || core.mcpToolKinds.length > 0
186
- ? [POLL_RUN_TOOL_DEFINITION]
187
- : []),
188
- ...surface
189
- .filter((tool) => !taken.has(String(tool.definition.name)))
190
- .map((tool) => tool.definition),
191
- ],
192
- };
193
- }
194
- case "resources/list":
195
- return { resources: [] };
196
- case "resources/templates/list":
197
- return { resourceTemplates: [] };
198
- case "prompts/list":
199
- return { prompts: [] };
200
- case "tools/call": {
201
- const name = typeof params.name === "string" ? params.name : "";
202
- const args =
203
- typeof params.arguments === "object" && params.arguments !== null
204
- ? (params.arguments as Record<string, unknown>)
205
- : {};
206
- const gatewayTool = gatewayTools.find((tool) => tool.name === name);
207
- if (gatewayTool) {
208
- try {
209
- return toolValue(
210
- await gatewayTool.execute(args, {
211
- projectId,
212
- sessionId,
213
- // An MCP call hears nothing of its turn: it waits while
214
- // asked (ADR 0264).
215
- stopWaiting: abort.signal,
216
- }),
217
- );
218
- } catch (error) {
219
- return toolError(
220
- error instanceof Error ? error.message : "Capability failed",
221
- );
222
- }
223
- }
224
- const workflowTools = await loadProjectTools(
225
- core,
226
- identity,
227
- projectId,
228
- );
229
- const surfaced = workflowTools.some((tool) => tool.name === name)
230
- ? undefined
231
- : surface.find((tool) => tool.definition.name === name);
232
- if (surfaced) return surfaced.call(args);
233
- return callTool(core, identity, projectId, name, args);
234
- }
235
- default:
236
- throw new McpRequestError(-32601, `Method not found: ${method}`);
237
- }
238
- });
239
- });
255
+ tools,
256
+ withheld: async () => withheldTools(identity, await allTools()),
257
+ ...(chats ? { resources: chats.resources, tasks: chats.tasks } : {}),
258
+ },
259
+ });
260
+ },
261
+ );
240
262
  }
241
263
 
242
264
  /**
@@ -263,6 +263,7 @@ export function registerProjectRoutes(app: FastifyInstance, ctx: RouteContext) {
263
263
  typed.route({
264
264
  method: "PUT",
265
265
  url: "/projects/:projectId/files/*",
266
+ config: { tokenScope: "program:write" },
266
267
  schema: {
267
268
  params: ProjectFileParamsSchema,
268
269
  body: WriteFileSchema,
@@ -444,6 +445,7 @@ export function registerProjectRoutes(app: FastifyInstance, ctx: RouteContext) {
444
445
  typed.route({
445
446
  method: "POST",
446
447
  url: "/projects/:projectId/deploy",
448
+ config: { tokenScope: "program:publish" },
447
449
  schema: {
448
450
  params: ProjectIdParamsSchema,
449
451
  body: DeployRequestSchema,
@@ -502,6 +504,7 @@ export function registerProjectRoutes(app: FastifyInstance, ctx: RouteContext) {
502
504
  typed.route({
503
505
  method: "POST",
504
506
  url: "/projects/:projectId/pull",
507
+ config: { tokenScope: "program:write" },
505
508
  schema: {
506
509
  params: ProjectIdParamsSchema,
507
510
  body: PullRequestSchema,
@@ -538,6 +541,7 @@ export function registerProjectRoutes(app: FastifyInstance, ctx: RouteContext) {
538
541
  typed.route({
539
542
  method: "POST",
540
543
  url: "/projects/:projectId/discard",
544
+ config: { tokenScope: "program:write" },
541
545
  schema: {
542
546
  params: ProjectIdParamsSchema,
543
547
  response: {
@@ -572,6 +576,7 @@ export function registerProjectRoutes(app: FastifyInstance, ctx: RouteContext) {
572
576
  typed.route({
573
577
  method: "POST",
574
578
  url: "/projects/:projectId/resolve-conflicts",
579
+ config: { tokenScope: "program:write" },
575
580
  schema: {
576
581
  params: ProjectIdParamsSchema,
577
582
  body: ResolveConflictsSchema,
@@ -611,6 +616,7 @@ export function registerProjectRoutes(app: FastifyInstance, ctx: RouteContext) {
611
616
  typed.route({
612
617
  method: "POST",
613
618
  url: "/projects/:projectId/ai-resolve-conflicts",
619
+ config: { tokenScope: "program:write" },
614
620
  schema: {
615
621
  params: ProjectIdParamsSchema,
616
622
  body: z.object({
@@ -75,6 +75,7 @@ export function registerPublicationRoutes(
75
75
  typed.route({
76
76
  method: "POST",
77
77
  url: "/projects/:projectId/publications",
78
+ config: { tokenScope: "program:publish" },
78
79
  schema: {
79
80
  params: ProjectIdParamsSchema,
80
81
  body: PublishSchema,
@@ -137,6 +138,7 @@ export function registerPublicationRoutes(
137
138
  typed.route({
138
139
  method: "DELETE",
139
140
  url: "/projects/:projectId/publications/:slug",
141
+ config: { tokenScope: "program:publish" },
140
142
  schema: {
141
143
  params: PublicationParamsSchema,
142
144
  response: { 204: z.null(), 404: ErrorSchema },
@@ -12,6 +12,7 @@ import {
12
12
  RunCapabilityError,
13
13
  RunEnrollmentConflictError,
14
14
  RunInputInvalidError,
15
+ RunQueueFullError,
15
16
  SandboxProviderNotConfiguredError,
16
17
  TenantActiveRunLimitError,
17
18
  WorkflowNotFoundError,
@@ -36,7 +37,10 @@ export function replyForTriggerError(
36
37
  if (err instanceof ProductionDeploymentNotFoundError) {
37
38
  return reply.status(409).send({ error: err.message });
38
39
  }
39
- if (err instanceof RunEnrollmentConflictError) {
40
+ if (
41
+ err instanceof RunEnrollmentConflictError ||
42
+ err instanceof RunQueueFullError
43
+ ) {
40
44
  return reply.status(409).send({ error: err.message });
41
45
  }
42
46
  if (err instanceof AuthenticationRequiredError) {
@@ -57,6 +57,7 @@ export function registerRunRoutes(app: FastifyInstance, ctx: RouteContext) {
57
57
  typed.route({
58
58
  method: "POST",
59
59
  url: "/runs/:runId/cancel",
60
+ config: { tokenScope: "sessions:run" },
60
61
  schema: {
61
62
  params: RunIdParamsSchema,
62
63
  body: CancelRunSchema,
@@ -87,6 +88,7 @@ export function registerRunRoutes(app: FastifyInstance, ctx: RouteContext) {
87
88
  typed.route({
88
89
  method: "POST",
89
90
  url: "/runs/:runId/pause",
91
+ config: { tokenScope: "sessions:run" },
90
92
  schema: {
91
93
  params: RunIdParamsSchema,
92
94
  response: {
@@ -115,6 +117,7 @@ export function registerRunRoutes(app: FastifyInstance, ctx: RouteContext) {
115
117
  typed.route({
116
118
  method: "POST",
117
119
  url: "/runs/:runId/resume",
120
+ config: { tokenScope: "sessions:run" },
118
121
  schema: {
119
122
  params: RunIdParamsSchema,
120
123
  response: {
@@ -143,6 +146,7 @@ export function registerRunRoutes(app: FastifyInstance, ctx: RouteContext) {
143
146
  typed.route({
144
147
  method: "POST",
145
148
  url: "/runs/:runId/pauses/:pauseId/resume",
149
+ config: { tokenScope: "sessions:run" },
146
150
  schema: {
147
151
  params: RunPauseParamsSchema,
148
152
  body: ResumeRunPauseSchema,
@@ -0,0 +1,151 @@
1
+ import type { CatamorphicCore, Identity } from "@catamorphic/core";
2
+ import type { FastifyInstance, FastifyReply } from "fastify";
3
+ import { z } from "zod";
4
+ import type { RouteContext } from "../app.js";
5
+ import { resolveIdentity } from "../http-identity.js";
6
+ import { mayCallTool, mcpStateSecret, withheldTools } from "../mcp-scopes.js";
7
+ import { type McpTool, serveMcp } from "../mcp-server.js";
8
+ import { toolError, toolValue } from "../mcp-shared.js";
9
+ import { sessionMcp } from "../session-mcp.js";
10
+
11
+ /**
12
+ * The server's own MCP endpoint (ADR 0347): the one address a person
13
+ * gives their agent. It serves `project_list` and the session operations
14
+ * with the project as an argument, so one connection starts, watches and
15
+ * answers chats in every project its person may use. A project's own
16
+ * endpoint (`/projects/:projectId/mcp`) adds that project's documents,
17
+ * program and workflows, with the same chat tools bound to it.
18
+ */
19
+
20
+ /**
21
+ * What every client is told first. The first 512 characters stand alone:
22
+ * some clients read no further.
23
+ */
24
+ export const SERVER_MCP_INSTRUCTIONS =
25
+ "Work runs coding agents on this server as you. Start one with session_start (it returns a sessionId at once), keep working, then call session_wait with the returned cursor until state is idle, failed or needs_input. needs_input lists requests: answer questions with session_answer; approvals go to your person. Read replies, typed results and pull requests with session_read. Steer with session_send, stop with session_interrupt. Retry any call with the same idempotencyKey.\n\nproject_list names the projects you may use and their agents: pass a project's id as project to session_start and session_list. Every chat tool answers with the chat's state (working, needs_input, idle, failed or closed) and a cursor. A wait returns within 50 seconds; changed false means nothing happened yet, so call it again with the same cursor. A project's own endpoint, at /projects/<id>/mcp beside this one, adds its documents, program and workflows.";
26
+
27
+ const ProjectListOutput = z.object({
28
+ projects: z.array(
29
+ z.object({
30
+ id: z.string(),
31
+ name: z.string(),
32
+ /** The agents a chat can start on, by the id session_start takes. */
33
+ agents: z.array(
34
+ z.object({
35
+ id: z.string(),
36
+ name: z.string(),
37
+ description: z.string().optional(),
38
+ default: z.boolean().optional(),
39
+ }),
40
+ ),
41
+ }),
42
+ ),
43
+ });
44
+
45
+ function projectListTool(core: CatamorphicCore, identity: Identity): McpTool {
46
+ return {
47
+ definition: {
48
+ name: "project_list",
49
+ title: "List projects",
50
+ description:
51
+ "List the projects you may use on this server, each with the agents you can start a chat on. Use it first: session_start and session_list take a project's id. Next: session_start.",
52
+ inputSchema: { type: "object", properties: {} },
53
+ outputSchema: z.toJSONSchema(ProjectListOutput),
54
+ annotations: {
55
+ title: "List projects",
56
+ readOnlyHint: true,
57
+ idempotentHint: true,
58
+ openWorldHint: false,
59
+ },
60
+ },
61
+ scope: "work:read",
62
+ call: async () => {
63
+ try {
64
+ const { items } = await core.projects.list(identity, { limit: 100 });
65
+ const projects = [];
66
+ for (const project of items) {
67
+ // A project whose agents the caller may not see lists none.
68
+ const catalog = await core.agentSessions
69
+ ?.catalog({ identity, projectId: project.id })
70
+ .catch(() => undefined);
71
+ projects.push({
72
+ id: project.id,
73
+ name: project.name,
74
+ agents: (catalog?.items ?? [])
75
+ .filter((agent) => agent.available)
76
+ .map((agent) => ({
77
+ id: agent.id,
78
+ name: agent.name,
79
+ ...(agent.description
80
+ ? { description: agent.description }
81
+ : {}),
82
+ ...(agent.id === catalog?.defaultAgentId
83
+ ? { default: true }
84
+ : {}),
85
+ })),
86
+ });
87
+ }
88
+ return toolValue(ProjectListOutput.parse({ projects }));
89
+ } catch (error) {
90
+ return toolError(
91
+ error instanceof Error ? error.message : String(error),
92
+ );
93
+ }
94
+ },
95
+ };
96
+ }
97
+
98
+ export function registerServerMcpRoutes(
99
+ app: FastifyInstance,
100
+ ctx: RouteContext,
101
+ ) {
102
+ // Stateless Streamable HTTP: no server-initiated stream, no session to end.
103
+ const notAllowed = async (_request: unknown, reply: FastifyReply) =>
104
+ reply.status(405).header("allow", "POST").send();
105
+ app.get("/mcp", notAllowed);
106
+ app.delete("/mcp", { config: { tokenScope: "work:read" } }, notAllowed);
107
+
108
+ app.post(
109
+ "/mcp",
110
+ { config: { tokenScope: "work:read" } },
111
+ async (request, reply) => {
112
+ const core = ctx.core;
113
+ if (!core)
114
+ return reply.status(503).send({ error: "Service not configured" });
115
+ if (!ctx.features.mcp)
116
+ return reply
117
+ .status(404)
118
+ .send({ error: "MCP is turned off on this server" });
119
+ const identity = resolveIdentity(request);
120
+ const chats = sessionMcp({
121
+ core,
122
+ identity,
123
+ stateSecret: mcpStateSecret(ctx),
124
+ });
125
+ const all: McpTool[] = [
126
+ projectListTool(core, identity),
127
+ ...(chats?.tools ?? []),
128
+ ];
129
+ return serveMcp({
130
+ request,
131
+ reply,
132
+ ...(ctx.mcp?.resourceMetadataUrl
133
+ ? { resourceMetadataUrl: ctx.mcp.resourceMetadataUrl }
134
+ : {}),
135
+ endpoint: {
136
+ serverInfo: {
137
+ version: "1.0.0",
138
+ ...(ctx.projectMcp?.serverInfo ?? {
139
+ name: "catamorphic",
140
+ title: "Catamorphic",
141
+ }),
142
+ },
143
+ instructions: async () => SERVER_MCP_INSTRUCTIONS,
144
+ tools: async () => all.filter((tool) => mayCallTool(identity, tool)),
145
+ withheld: async () => withheldTools(identity, all),
146
+ ...(chats ? { resources: chats.resources, tasks: chats.tasks } : {}),
147
+ },
148
+ });
149
+ },
150
+ );
151
+ }
@@ -49,6 +49,7 @@ export function registerSessionMailboxRoutes(
49
49
  typed.route({
50
50
  method: "POST",
51
51
  url: "/projects/:projectId/session-mailboxes/:mailboxId/acknowledge",
52
+ config: { tokenScope: "sessions:run" },
52
53
  schema: {
53
54
  params: SessionMailboxIdParamsSchema,
54
55
  body: AcknowledgeSessionMailboxSchema,