@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
package/src/mcp-shared.ts CHANGED
@@ -1,115 +1,13 @@
1
1
  import type { CatamorphicCore, Identity } from "@catamorphic/core";
2
2
  import { MCP_POLL_RUN_TOOL, RunNotFoundError } from "@catamorphic/core";
3
- import type { FastifyReply } from "fastify";
4
3
  import { z } from "zod";
5
4
 
6
5
  /**
7
- * The JSON-RPC / MCP plumbing shared by the plugin's MCP endpoints — the
8
- * apps server (`/projects/:id/apps-mcp`), the workflow-tools server
9
- * (`/projects/:id/mcp`) and the connection broker (`/connection-mcp`) —
10
- * and by hosts that forward MCP servers of their own. All are stateless
11
- * Streamable-HTTP handlers speaking the `initialize`-handshake protocol era
12
- * (≤2025-11-25): requests are independent, no sessions, notifications
13
- * answered with a bare 202.
6
+ * What the plugin's MCP endpoints share beside the dispatcher
7
+ * (`mcp-server.ts`): how a value becomes a tool result, how another
8
+ * server's tools and results are forwarded, and the run poll tool.
14
9
  */
15
10
 
16
- export interface JsonRpcMessage {
17
- jsonrpc?: string;
18
- id?: number | string | null;
19
- method?: string;
20
- params?: Record<string, unknown>;
21
- }
22
-
23
- export const SUPPORTED_PROTOCOL_VERSIONS = new Set([
24
- "2024-11-05",
25
- "2025-03-26",
26
- "2025-06-18",
27
- "2025-11-25",
28
- ]);
29
- export const DEFAULT_PROTOCOL_VERSION = "2025-06-18";
30
-
31
- /** The requested revision when supported, our default otherwise. */
32
- export function negotiateProtocolVersion(requested: unknown): string {
33
- return typeof requested === "string" &&
34
- SUPPORTED_PROTOCOL_VERSIONS.has(requested)
35
- ? requested
36
- : DEFAULT_PROTOCOL_VERSION;
37
- }
38
-
39
- /** A dispatch failure that should ride a specific JSON-RPC error code. */
40
- export class McpRequestError extends Error {
41
- constructor(
42
- readonly code: number,
43
- message: string,
44
- ) {
45
- super(message);
46
- this.name = "McpRequestError";
47
- }
48
- }
49
-
50
- /**
51
- * The stateless request shell the endpoints share: body-shape validation,
52
- * the notification 202, missing-method rejection, and error mapping.
53
- * `dispatch` returns the JSON-RPC result for a method; it throws
54
- * {@link McpRequestError} for coded failures (-32601 method-not-found,
55
- * -32602 bad params) and anything else becomes -32603.
56
- */
57
- export async function handleMcpPost(
58
- reply: FastifyReply,
59
- body: unknown,
60
- dispatch: (
61
- method: string,
62
- params: Record<string, unknown>,
63
- ) => Promise<unknown>,
64
- ): Promise<FastifyReply> {
65
- const message = body as JsonRpcMessage | null;
66
- if (!message || typeof message !== "object" || Array.isArray(message)) {
67
- return rpcError(reply, null, -32600, "Expected a single JSON-RPC message");
68
- }
69
- // Notifications (initialized, cancelled, …) need no body in return.
70
- if (message.id === undefined || message.id === null) {
71
- return reply.status(202).send();
72
- }
73
- if (typeof message.method !== "string") {
74
- return rpcError(reply, message.id, -32600, "Missing method");
75
- }
76
- try {
77
- const result = await dispatch(message.method, message.params ?? {});
78
- return rpcResult(reply, message.id, result);
79
- } catch (error) {
80
- if (error instanceof McpRequestError) {
81
- return rpcError(reply, message.id, error.code, error.message);
82
- }
83
- return rpcError(
84
- reply,
85
- message.id,
86
- -32603,
87
- error instanceof Error ? error.message : "Internal error",
88
- );
89
- }
90
- }
91
-
92
- export function rpcResult(
93
- reply: FastifyReply,
94
- id: number | string,
95
- result: unknown,
96
- ): FastifyReply {
97
- return reply
98
- .header("content-type", "application/json")
99
- .send({ jsonrpc: "2.0", id, result });
100
- }
101
-
102
- export function rpcError(
103
- reply: FastifyReply,
104
- id: number | string | null,
105
- code: number,
106
- message: string,
107
- ): FastifyReply {
108
- return reply
109
- .header("content-type", "application/json")
110
- .send({ jsonrpc: "2.0", id, error: { code, message } });
111
- }
112
-
113
11
  /**
114
12
  * Tool result: JSON text for model readability plus `structuredContent`
115
13
  * for structured consumers. MCP defines structured content as a JSON
@@ -283,49 +181,3 @@ export interface ForwardedToolDefinition {
283
181
  outputSchema?: unknown;
284
182
  annotations?: unknown;
285
183
  }
286
-
287
- const CallParamsSchema = z.object({
288
- name: z.string().min(1),
289
- arguments: z.record(z.string(), z.unknown()).default({}),
290
- });
291
-
292
- /**
293
- * A stateless MCP endpoint serving another server's tools: tools listed
294
- * and results returned as that server declared and sent them (ADR 0225).
295
- * `callTool` answers with the server's own result (any tool result, such
296
- * as {@link toolError}, passes through), or throws {@link McpRequestError}
297
- * for a refusal at the protocol boundary.
298
- */
299
- export function serveForwardedTools(args: {
300
- reply: FastifyReply;
301
- body: unknown;
302
- serverName: string;
303
- listTools(): Promise<readonly ForwardedToolDefinition[]>;
304
- callTool(call: {
305
- name: string;
306
- arguments: Record<string, unknown>;
307
- }): Promise<unknown>;
308
- }): Promise<FastifyReply> {
309
- return handleMcpPost(args.reply, args.body, async (method, params) => {
310
- switch (method) {
311
- case "initialize":
312
- return {
313
- protocolVersion: negotiateProtocolVersion(params.protocolVersion),
314
- capabilities: { tools: {} },
315
- serverInfo: { name: args.serverName, version: "1" },
316
- };
317
- case "ping":
318
- return {};
319
- case "tools/list":
320
- return { tools: (await args.listTools()).map(forwardedTool) };
321
- case "tools/call": {
322
- const call = CallParamsSchema.safeParse(params);
323
- if (!call.success)
324
- throw new McpRequestError(-32602, "Invalid tool call");
325
- return forwardedToolResult(await args.callTool(call.data));
326
- }
327
- default:
328
- throw new McpRequestError(-32601, "Method not found");
329
- }
330
- });
331
- }
package/src/mcp.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * MCP serving for hosts: an endpoint that forwards another MCP server's
3
- * tools the way the plugin's own connection endpoint does (ADR 0225).
3
+ * tools the way the plugin's own connection endpoint does (ADR 0225), on
4
+ * the dispatcher every MCP endpoint shares (ADR 0347).
4
5
  */
5
6
  export {
6
- type ForwardedToolDefinition,
7
- McpRequestError,
7
+ MCP_ERROR,
8
+ McpError,
8
9
  serveForwardedTools,
9
- toolError,
10
- } from "./mcp-shared.js";
10
+ } from "./mcp-server.js";
11
+ export { type ForwardedToolDefinition, toolError } from "./mcp-shared.js";
package/src/plugin.ts CHANGED
@@ -1,13 +1,16 @@
1
- import type { CatamorphicCore, Identity } from "@catamorphic/core";
1
+ import type { CatamorphicCore, Identity, TokenScope } from "@catamorphic/core";
2
2
  import {
3
3
  AccessDeniedError,
4
4
  DeploymentBlockedError,
5
5
  EnvironmentPolicyInvalidError,
6
+ FULL_TOKEN_SCOPE,
7
+ hasTokenScope,
6
8
  ProjectNotFoundError,
7
9
  ServerDraftError,
8
10
  SessionArtifactConflictError,
9
11
  SessionArtifactNotFoundError,
10
12
  SessionArtifactValidationError,
13
+ TokenScopeRequiredError,
11
14
  } from "@catamorphic/core";
12
15
  import {
13
16
  DraftBinaryResolutionError,
@@ -22,7 +25,7 @@ import {
22
25
  NoDraftError,
23
26
  RefMovedError,
24
27
  } from "@catamorphic/git";
25
- import type { FastifyPluginAsync } from "fastify";
28
+ import type { FastifyPluginAsync, FastifyReply } from "fastify";
26
29
  import {
27
30
  serializerCompiler,
28
31
  validatorCompiler,
@@ -57,6 +60,7 @@ import { registerProjectMcpRoutes } from "./routes/project-mcp.js";
57
60
  import { registerProjectRoutes } from "./routes/projects.js";
58
61
  import { registerPublicationRoutes } from "./routes/publications.js";
59
62
  import { registerRunRoutes } from "./routes/runs.js";
63
+ import { registerServerMcpRoutes } from "./routes/server-mcp.js";
60
64
  import { registerSessionArtifactRoutes } from "./routes/session-artifacts.js";
61
65
  import { registerSessionMailboxRoutes } from "./routes/session-mailboxes.js";
62
66
  import { registerSessionPreviewRoutes } from "./routes/session-previews.js";
@@ -67,6 +71,13 @@ import { registerWebhookRoutes } from "./routes/webhooks.js";
67
71
  import { registerWorkflowEnablementRoutes } from "./routes/workflow-enablements.js";
68
72
  import { registerWorkflowRoutes } from "./routes/workflows.js";
69
73
 
74
+ declare module "fastify" {
75
+ interface FastifyContextConfig {
76
+ /** OAuth scope required for a member to call this route. */
77
+ tokenScope?: TokenScope;
78
+ }
79
+ }
80
+
70
81
  export interface CatamorphicPluginOptions {
71
82
  /**
72
83
  * Wired catamorphic services (build them with `@catamorphic/server-sdk` or
@@ -110,6 +121,19 @@ export interface CatamorphicPluginOptions {
110
121
  publicApiBase?: string;
111
122
  /** Host additions to the project MCP endpoint (ADR 0166). */
112
123
  projectMcp?: ProjectMcpHost;
124
+ /** What the MCP endpoints need from a host with replicas or OAuth. */
125
+ mcp?: McpHost;
126
+ }
127
+
128
+ /**
129
+ * Host settings for the MCP endpoints (ADR 0347). `stateSecret` signs the
130
+ * state a wait hands a client with what it asks; replicas must share it,
131
+ * and a host that sets none gets one per process. `resourceMetadataUrl`
132
+ * is the OAuth protected-resource document a step-up challenge names.
133
+ */
134
+ export interface McpHost {
135
+ stateSecret?: string;
136
+ resourceMetadataUrl?: string;
113
137
  }
114
138
 
115
139
  /**
@@ -162,6 +186,7 @@ export interface RouteContext {
162
186
  features: HostFeatures;
163
187
  publicApiBase?: string;
164
188
  projectMcp?: ProjectMcpHost;
189
+ mcp?: McpHost;
165
190
  }
166
191
 
167
192
  /**
@@ -182,6 +207,36 @@ export interface RouteContext {
182
207
  * mechanism; there is no header fallback unless the host opts into
183
208
  * `identityFromHeaders()` explicitly.
184
209
  */
210
+ /**
211
+ * 403 with the scope to ask for (RFC 6750), for a grant that lacks one:
212
+ * the same answer over REST and both MCP endpoints.
213
+ */
214
+ export function insufficientScope(
215
+ reply: FastifyReply,
216
+ scope: TokenScope,
217
+ mcp: McpHost | undefined,
218
+ ): FastifyReply {
219
+ return (
220
+ reply
221
+ .status(403)
222
+ .header(
223
+ "www-authenticate",
224
+ `Bearer error="insufficient_scope", scope="${scope}"${
225
+ mcp?.resourceMetadataUrl
226
+ ? `, resource_metadata="${mcp.resourceMetadataUrl}"`
227
+ : ""
228
+ }`,
229
+ )
230
+ // A body every route's declared 403 can carry.
231
+ .send({
232
+ error: `This needs the ${scope} scope, which this client was not granted.`,
233
+ code: "not_authorized",
234
+ retryable: false,
235
+ scope,
236
+ })
237
+ );
238
+ }
239
+
185
240
  export const catamorphicPlugin: FastifyPluginAsync<
186
241
  CatamorphicPluginOptions
187
242
  > = async (app, opts) => {
@@ -199,6 +254,9 @@ export const catamorphicPlugin: FastifyPluginAsync<
199
254
  ) {
200
255
  return reply.status(err.statusCode).send({ error: err.message });
201
256
  }
257
+ // The grant lacks a scope the call needs: a step-up challenge names it.
258
+ if (err instanceof TokenScopeRequiredError)
259
+ return insufficientScope(reply, err.scope, opts.mcp);
202
260
  if (err instanceof AccessDeniedError) {
203
261
  return reply.status(403).send({ error: err.message });
204
262
  }
@@ -273,6 +331,17 @@ export const catamorphicPlugin: FastifyPluginAsync<
273
331
  if (isPublic) return;
274
332
  return reply.status(401).send({ error: "Unauthorized" });
275
333
  }
334
+ // A client reads only what its person let it read (ADR 0347): no
335
+ // route is a way around a grant without `work:read`.
336
+ if (!isPublic && !hasTokenScope(identity, "work:read"))
337
+ return insufficientScope(reply, "work:read", opts.mcp);
338
+ const tokenScope =
339
+ request.routeOptions.config.tokenScope ??
340
+ (request.method === "GET" || request.method === "HEAD"
341
+ ? "work:read"
342
+ : FULL_TOKEN_SCOPE);
343
+ if (!isPublic && !hasTokenScope(identity, tokenScope))
344
+ return insufficientScope(reply, tokenScope, opts.mcp);
276
345
  const runnerId = request.headers["x-catamorphic-runner"];
277
346
  attachIdentity(
278
347
  request,
@@ -285,6 +354,7 @@ export const catamorphicPlugin: FastifyPluginAsync<
285
354
  const ctx: RouteContext = {
286
355
  core: opts.core,
287
356
  ...(opts.projectMcp ? { projectMcp: opts.projectMcp } : {}),
357
+ ...(opts.mcp ? { mcp: opts.mcp } : {}),
288
358
  ...(opts.publicApiBase
289
359
  ? { publicApiBase: opts.publicApiBase.replace(/\/$/, "") }
290
360
  : {}),
@@ -327,6 +397,7 @@ export const catamorphicPlugin: FastifyPluginAsync<
327
397
  registerPrivateCustomizationRoutes(app, ctx);
328
398
  registerAppsMcpRoutes(app, ctx);
329
399
  registerProjectMcpRoutes(app, ctx);
400
+ registerServerMcpRoutes(app, ctx);
330
401
  registerAgentCapabilityRoutes(app, ctx);
331
402
  registerCodeHostRoutes(app, ctx);
332
403
  registerPluginRoutes(app, ctx);
@@ -30,11 +30,13 @@ const OWN_CHAT_TOOLS = new Set([
30
30
  "set_session_metadata",
31
31
  ]);
32
32
 
33
- const Definition = z.object({
33
+ const Definition = z.looseObject({
34
34
  name: z.string(),
35
35
  description: z.string().default(""),
36
36
  inputSchema: z.record(z.string(), z.unknown()),
37
- annotations: z.object({ readOnlyHint: z.boolean().optional() }).optional(),
37
+ annotations: z
38
+ .looseObject({ readOnlyHint: z.boolean().optional() })
39
+ .optional(),
38
40
  });
39
41
 
40
42
  /** Internal projection of the public project tools. Both call the same services. */
@@ -124,7 +126,7 @@ export async function projectToolCapabilities(args: {
124
126
  "session_artifact",
125
127
  "create_watcher",
126
128
  "list_watchers",
127
- "stop_watcher",
129
+ "session_stop_watcher",
128
130
  ].includes(definition.name);
129
131
  const result = await tool.call(
130
132
  owned ? { ...values, sessionId: context.sessionId } : values,
@@ -598,9 +598,9 @@ export async function projectInstructions(args: {
598
598
  lines.push(
599
599
  "- Run deployed workflows with workflow_run and debug them with workflow_runs and run_details.",
600
600
  );
601
- if (has("ask_agent"))
601
+ if (has("session_start"))
602
602
  lines.push(
603
- "- ask_agent runs one of the project's agents on the server, in an Environment you may use. Server agents reach connected systems, such as a production database, through the reviewed gateway; you never receive those credentials.",
603
+ "- Run one of the project's agents on the server with session_start: it returns a sessionId at once, so keep working and call session_wait with the returned cursor until state is idle, failed or needs_input. Answer its questions with session_answer; approvals go to your person. Server agents reach connected systems, such as a production database, through the reviewed gateway; you never receive those credentials.",
604
604
  );
605
605
  if (args.host) lines.push(args.host);
606
606
  return lines.join("\n");