@catamorphic/fastify-plugin 0.0.0-stage → 0.1.0-alpha.31

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 (160) hide show
  1. package/LICENSE.txt +202 -0
  2. package/NOTICE.txt +32 -0
  3. package/README.md +143 -2
  4. package/dist/app-presentation-tools.d.ts +4 -0
  5. package/dist/app-presentation-tools.d.ts.map +1 -0
  6. package/dist/app.d.ts +27 -0
  7. package/dist/app.d.ts.map +1 -0
  8. package/dist/chunk-baagvvm3.js +164 -0
  9. package/dist/chunk-baagvvm3.js.map +10 -0
  10. package/dist/http-identity.d.ts +52 -0
  11. package/dist/http-identity.d.ts.map +1 -0
  12. package/dist/hung-up.d.ts +7 -0
  13. package/dist/hung-up.d.ts.map +1 -0
  14. package/dist/index.d.ts +11 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +10884 -0
  17. package/dist/index.js.map +56 -0
  18. package/dist/mcp-shared.d.ts +117 -0
  19. package/dist/mcp-shared.d.ts.map +1 -0
  20. package/dist/mcp.d.ts +6 -0
  21. package/dist/mcp.d.ts.map +1 -0
  22. package/dist/mcp.js +13 -0
  23. package/dist/mcp.js.map +9 -0
  24. package/dist/plugin.d.ts +113 -0
  25. package/dist/plugin.d.ts.map +1 -0
  26. package/dist/project-capabilities.d.ts +25 -0
  27. package/dist/project-capabilities.d.ts.map +1 -0
  28. package/dist/project-mcp-program.d.ts +15 -0
  29. package/dist/project-mcp-program.d.ts.map +1 -0
  30. package/dist/project-mcp-surface.d.ts +16 -0
  31. package/dist/project-mcp-surface.d.ts.map +1 -0
  32. package/dist/request-logging.d.ts +18 -0
  33. package/dist/request-logging.d.ts.map +1 -0
  34. package/dist/routes/agent-capabilities.d.ts +4 -0
  35. package/dist/routes/agent-capabilities.d.ts.map +1 -0
  36. package/dist/routes/agent.d.ts +4 -0
  37. package/dist/routes/agent.d.ts.map +1 -0
  38. package/dist/routes/apps-mcp.d.ts +4 -0
  39. package/dist/routes/apps-mcp.d.ts.map +1 -0
  40. package/dist/routes/apps.d.ts +12 -0
  41. package/dist/routes/apps.d.ts.map +1 -0
  42. package/dist/routes/client-runners.d.ts +11 -0
  43. package/dist/routes/client-runners.d.ts.map +1 -0
  44. package/dist/routes/code-hosts.d.ts +11 -0
  45. package/dist/routes/code-hosts.d.ts.map +1 -0
  46. package/dist/routes/connection-mcp.d.ts +10 -0
  47. package/dist/routes/connection-mcp.d.ts.map +1 -0
  48. package/dist/routes/connections.d.ts +4 -0
  49. package/dist/routes/connections.d.ts.map +1 -0
  50. package/dist/routes/documents.d.ts +11 -0
  51. package/dist/routes/documents.d.ts.map +1 -0
  52. package/dist/routes/environments.d.ts +4 -0
  53. package/dist/routes/environments.d.ts.map +1 -0
  54. package/dist/routes/git-gateway.d.ts +21 -0
  55. package/dist/routes/git-gateway.d.ts.map +1 -0
  56. package/dist/routes/http-gateway.d.ts +13 -0
  57. package/dist/routes/http-gateway.d.ts.map +1 -0
  58. package/dist/routes/me.d.ts +12 -0
  59. package/dist/routes/me.d.ts.map +1 -0
  60. package/dist/routes/memberships.d.ts +12 -0
  61. package/dist/routes/memberships.d.ts.map +1 -0
  62. package/dist/routes/model-gateway.d.ts +12 -0
  63. package/dist/routes/model-gateway.d.ts.map +1 -0
  64. package/dist/routes/notifications.d.ts +4 -0
  65. package/dist/routes/notifications.d.ts.map +1 -0
  66. package/dist/routes/parse.d.ts +5 -0
  67. package/dist/routes/parse.d.ts.map +1 -0
  68. package/dist/routes/personal-environment.d.ts +13 -0
  69. package/dist/routes/personal-environment.d.ts.map +1 -0
  70. package/dist/routes/plugins.d.ts +4 -0
  71. package/dist/routes/plugins.d.ts.map +1 -0
  72. package/dist/routes/project-mcp.d.ts +25 -0
  73. package/dist/routes/project-mcp.d.ts.map +1 -0
  74. package/dist/routes/projects.d.ts +4 -0
  75. package/dist/routes/projects.d.ts.map +1 -0
  76. package/dist/routes/publications.d.ts +15 -0
  77. package/dist/routes/publications.d.ts.map +1 -0
  78. package/dist/routes/run-errors.d.ts +8 -0
  79. package/dist/routes/run-errors.d.ts.map +1 -0
  80. package/dist/routes/runs.d.ts +4 -0
  81. package/dist/routes/runs.d.ts.map +1 -0
  82. package/dist/routes/session-artifacts.d.ts +27 -0
  83. package/dist/routes/session-artifacts.d.ts.map +1 -0
  84. package/dist/routes/session-mailboxes.d.ts +4 -0
  85. package/dist/routes/session-mailboxes.d.ts.map +1 -0
  86. package/dist/routes/session-previews.d.ts +40 -0
  87. package/dist/routes/session-previews.d.ts.map +1 -0
  88. package/dist/routes/session-terminals.d.ts +15 -0
  89. package/dist/routes/session-terminals.d.ts.map +1 -0
  90. package/dist/routes/triggers.d.ts +20 -0
  91. package/dist/routes/triggers.d.ts.map +1 -0
  92. package/dist/routes/watchers.d.ts +4 -0
  93. package/dist/routes/watchers.d.ts.map +1 -0
  94. package/dist/routes/webhooks.d.ts +11 -0
  95. package/dist/routes/webhooks.d.ts.map +1 -0
  96. package/dist/routes/workflow-enablements.d.ts +4 -0
  97. package/dist/routes/workflow-enablements.d.ts.map +1 -0
  98. package/dist/routes/workflows.d.ts +4 -0
  99. package/dist/routes/workflows.d.ts.map +1 -0
  100. package/dist/schemas.d.ts +17776 -0
  101. package/dist/schemas.d.ts.map +1 -0
  102. package/dist/session-artifact-tools.d.ts +5 -0
  103. package/dist/session-artifact-tools.d.ts.map +1 -0
  104. package/dist/session-event-stream.d.ts +45 -0
  105. package/dist/session-event-stream.d.ts.map +1 -0
  106. package/dist/spa.d.ts +24 -0
  107. package/dist/spa.d.ts.map +1 -0
  108. package/dist/telemetry.d.ts +4 -0
  109. package/dist/telemetry.d.ts.map +1 -0
  110. package/package.json +73 -4
  111. package/src/app-presentation-tools.ts +46 -0
  112. package/src/app.ts +115 -0
  113. package/src/http-identity.ts +145 -0
  114. package/src/hung-up.ts +13 -0
  115. package/src/index.ts +25 -0
  116. package/src/mcp-shared.ts +331 -0
  117. package/src/mcp.ts +10 -0
  118. package/src/plugin.ts +332 -0
  119. package/src/project-capabilities.ts +153 -0
  120. package/src/project-mcp-program.ts +607 -0
  121. package/src/project-mcp-surface.ts +881 -0
  122. package/src/request-logging.ts +47 -0
  123. package/src/routes/agent-capabilities.ts +109 -0
  124. package/src/routes/agent.ts +1566 -0
  125. package/src/routes/apps-mcp.ts +303 -0
  126. package/src/routes/apps.ts +692 -0
  127. package/src/routes/client-runners.ts +251 -0
  128. package/src/routes/code-hosts.ts +247 -0
  129. package/src/routes/connection-mcp.ts +135 -0
  130. package/src/routes/connections.ts +494 -0
  131. package/src/routes/documents.ts +538 -0
  132. package/src/routes/environments.ts +72 -0
  133. package/src/routes/git-gateway.ts +106 -0
  134. package/src/routes/http-gateway.ts +141 -0
  135. package/src/routes/me.ts +122 -0
  136. package/src/routes/memberships.ts +173 -0
  137. package/src/routes/model-gateway.ts +134 -0
  138. package/src/routes/notifications.ts +101 -0
  139. package/src/routes/parse.ts +32 -0
  140. package/src/routes/personal-environment.ts +146 -0
  141. package/src/routes/plugins.ts +341 -0
  142. package/src/routes/project-mcp.ts +394 -0
  143. package/src/routes/projects.ts +708 -0
  144. package/src/routes/publications.ts +222 -0
  145. package/src/routes/run-errors.ts +86 -0
  146. package/src/routes/runs.ts +253 -0
  147. package/src/routes/session-artifacts.ts +293 -0
  148. package/src/routes/session-mailboxes.ts +80 -0
  149. package/src/routes/session-previews.ts +224 -0
  150. package/src/routes/session-terminals.ts +209 -0
  151. package/src/routes/triggers.ts +241 -0
  152. package/src/routes/watchers.ts +94 -0
  153. package/src/routes/webhooks.ts +171 -0
  154. package/src/routes/workflow-enablements.ts +331 -0
  155. package/src/routes/workflows.ts +323 -0
  156. package/src/schemas.ts +2735 -0
  157. package/src/session-artifact-tools.ts +170 -0
  158. package/src/session-event-stream.ts +122 -0
  159. package/src/spa.ts +135 -0
  160. package/src/telemetry.ts +93 -0
@@ -0,0 +1,881 @@
1
+ import {
2
+ SET_SESSION_METADATA_DESCRIPTION,
3
+ sessionMetadataToolWrite,
4
+ setSessionMetadataInputSchema,
5
+ } from "@catamorphic/agent-protocol";
6
+ import type { CatamorphicCore, Identity } from "@catamorphic/core";
7
+ import {
8
+ AccessDeniedError,
9
+ AgentTurnUnsettledError,
10
+ EVERY_ARTIFACT,
11
+ mayUseProject,
12
+ parseWorkspaceRequest,
13
+ projectAgentId,
14
+ resolveScope,
15
+ SESSION_ACTION_SCHEMAS,
16
+ type SessionActionOperation,
17
+ } from "@catamorphic/core";
18
+ import { z } from "zod";
19
+ import { appPresentationTool } from "./app-presentation-tools.js";
20
+ import { toolError, toolValue } from "./mcp-shared.js";
21
+ import { sessionArtifactTool } from "./session-artifact-tools.js";
22
+
23
+ /**
24
+ * The project's "bring your own agent" surface (ADR 0055): everything a
25
+ * caller's scope covers, as MCP tools beside the workflow tools —
26
+ *
27
+ * - documents: list / read / search / write / delete / history over the one
28
+ * path namespace (program + store), each narrowed to the caller's
29
+ * document refs by `DocumentsService` itself;
30
+ * - skills: list / read, for anyone who may use the project (with
31
+ * `program:read`, or an agent ref);
32
+ * - agents: `ask_agent` — a synchronous chat turn with a project agent the
33
+ * caller may open sessions on (`AgentSessionsService` enforces the ref).
34
+ *
35
+ * Nothing here checks scope by hand: every call goes through the core
36
+ * service that already enforces it, with the request's identity.
37
+ */
38
+
39
+ const READ_ONLY = { readOnlyHint: true } as const;
40
+
41
+ export interface SurfaceTool {
42
+ definition: Record<string, unknown>;
43
+ call: (args: Record<string, unknown>) => Promise<Record<string, unknown>>;
44
+ }
45
+
46
+ export { mayUseProject };
47
+
48
+ /** Workflow names a scoped caller may see on the tools list; null = all. */
49
+ export async function allowedWorkflowNames(
50
+ core: CatamorphicCore,
51
+ identity: Identity,
52
+ projectId: string,
53
+ ): Promise<ReadonlySet<string> | null> {
54
+ const resolved = await resolveScope({
55
+ db: core.db,
56
+ identity,
57
+ projectId,
58
+ policies: core.appPolicies,
59
+ });
60
+ return resolved?.allowedWorkflows ?? null;
61
+ }
62
+
63
+ export interface SurfaceFeatures {
64
+ publications: "public" | "members" | false;
65
+ proposals: boolean;
66
+ storeUploadMaxBytes?: number;
67
+ }
68
+
69
+ export function surfaceTools(
70
+ core: CatamorphicCore,
71
+ identity: Identity,
72
+ projectId: string,
73
+ features: SurfaceFeatures = { publications: "public", proposals: true },
74
+ currentSessionId?: string,
75
+ ): SurfaceTool[] {
76
+ const tools: SurfaceTool[] = [];
77
+ if (core.apps && mayUseProject(identity, projectId))
78
+ tools.push(appPresentationTool(core, identity, projectId));
79
+ if (
80
+ core.sessionArtifacts &&
81
+ core.agentSessions &&
82
+ mayUseProject(identity, projectId)
83
+ ) {
84
+ tools.push(
85
+ sessionArtifactTool(core, identity, projectId, currentSessionId),
86
+ );
87
+ }
88
+ const guarded =
89
+ (fn: (args: Record<string, unknown>) => Promise<unknown>) =>
90
+ async (args: Record<string, unknown>) => {
91
+ try {
92
+ return toolValue(await fn(args));
93
+ } catch (error) {
94
+ if (error instanceof AccessDeniedError) {
95
+ return toolError("Not authorized for that path or agent.");
96
+ }
97
+ return toolError(
98
+ error instanceof Error ? error.message : String(error),
99
+ );
100
+ }
101
+ };
102
+ const str = (v: unknown) => (typeof v === "string" ? v : undefined);
103
+ const int = (v: unknown) =>
104
+ typeof v === "number" && Number.isInteger(v) ? v : undefined;
105
+
106
+ if (core.documents) {
107
+ const documents = core.documents;
108
+ tools.push(
109
+ {
110
+ definition: {
111
+ name: "documents_storage",
112
+ description:
113
+ "Describe where this project's documents are saved, the file-size limit, and whether uploading is a separate action. Device means the computer serving this connection, not necessarily your own computer. A remote MCP connection saves remotely under that server's access rules.",
114
+ inputSchema: { type: "object", properties: {} },
115
+ annotations: READ_ONLY,
116
+ },
117
+ call: guarded(async () => {
118
+ const storage = await documents.storage({ identity, projectId });
119
+ return {
120
+ ...storage,
121
+ maxDocumentBytes: Math.min(
122
+ storage.maxDocumentBytes,
123
+ features.storeUploadMaxBytes ?? storage.maxDocumentBytes,
124
+ ),
125
+ };
126
+ }),
127
+ },
128
+ {
129
+ definition: {
130
+ name: "documents_list",
131
+ description:
132
+ "List the project's documents you may read — the program (docs, handbook, code, at the shared main) and the project store (store/…, per-customer notes, contracts, generated files; versioned, with author). Narrow with a prefix.",
133
+ inputSchema: {
134
+ type: "object",
135
+ properties: {
136
+ prefix: {
137
+ type: "string",
138
+ description:
139
+ "Directory prefix, e.g. docs or store/customers/acme",
140
+ },
141
+ source: { type: "string", enum: ["program", "store"] },
142
+ },
143
+ },
144
+ annotations: READ_ONLY,
145
+ },
146
+ call: guarded(async (args) =>
147
+ documents.list({
148
+ identity,
149
+ projectId,
150
+ ...(str(args.prefix) ? { prefix: str(args.prefix) } : {}),
151
+ ...(args.source === "program" || args.source === "store"
152
+ ? { source: args.source }
153
+ : {}),
154
+ }),
155
+ ),
156
+ },
157
+ {
158
+ definition: {
159
+ name: "documents_read",
160
+ description:
161
+ "Read one document (text content when text-like; metadata always). Store documents accept a version to read history. For a binary file, request encoding=base64 to receive its bytes. Saving through a remote MCP connection saves on that server, not on your device.",
162
+ inputSchema: {
163
+ type: "object",
164
+ properties: {
165
+ path: { type: "string" },
166
+ version: { type: "integer" },
167
+ encoding: { type: "string", enum: ["text", "base64"] },
168
+ },
169
+ required: ["path"],
170
+ },
171
+ annotations: READ_ONLY,
172
+ },
173
+ call: guarded(async (args) => {
174
+ if (args.encoding === "base64") {
175
+ const doc = await documents.readBytes({
176
+ identity,
177
+ projectId,
178
+ path: str(args.path) ?? "",
179
+ ...(int(args.version) !== undefined
180
+ ? { version: int(args.version) }
181
+ : {}),
182
+ });
183
+ if (doc.bytes.byteLength > 1024 * 1024)
184
+ throw new Error(
185
+ "This file is too large for an MCP text response. Download it from the authenticated documents/raw endpoint.",
186
+ );
187
+ const { bytes, ...entry } = doc;
188
+ return { ...entry, base64: Buffer.from(bytes).toString("base64") };
189
+ }
190
+ const doc = await documents.read({
191
+ identity,
192
+ projectId,
193
+ path: str(args.path) ?? "",
194
+ ...(int(args.version) !== undefined
195
+ ? { version: int(args.version) }
196
+ : {}),
197
+ });
198
+ const { bytes: _bytes, ...rest } = doc;
199
+ return rest;
200
+ }),
201
+ },
202
+ {
203
+ definition: {
204
+ name: "documents_search",
205
+ description:
206
+ "Search documents you may read. mode=grep (default): case-insensitive literal substring; mode=text: full-text, words in any order. Returns matching lines with line numbers. Prefer several small greps to one broad query.",
207
+ inputSchema: {
208
+ type: "object",
209
+ properties: {
210
+ query: { type: "string" },
211
+ mode: { type: "string", enum: ["grep", "text"] },
212
+ prefix: { type: "string" },
213
+ limit: { type: "integer" },
214
+ },
215
+ required: ["query"],
216
+ },
217
+ annotations: READ_ONLY,
218
+ },
219
+ call: guarded(async (args) =>
220
+ documents.search({
221
+ identity,
222
+ projectId,
223
+ query: str(args.query) ?? "",
224
+ ...(args.mode === "grep" || args.mode === "text"
225
+ ? { mode: args.mode }
226
+ : {}),
227
+ ...(str(args.prefix) ? { prefix: str(args.prefix) } : {}),
228
+ ...(int(args.limit) !== undefined
229
+ ? { limit: int(args.limit) }
230
+ : {}),
231
+ }),
232
+ ),
233
+ },
234
+ {
235
+ definition: {
236
+ name: "documents_write",
237
+ description:
238
+ "Write a store document (paths under store/ only; the program changes by commit). Give text, or base64 for binary content (a PDF, an image). Creates a new version stamped with you. Pass ifVersion (the version you read) to refuse overwriting someone else's newer write; 0 means 'must not exist yet'.",
239
+ inputSchema: {
240
+ type: "object",
241
+ properties: {
242
+ path: { type: "string" },
243
+ text: { type: "string" },
244
+ base64: {
245
+ type: "string",
246
+ description: "Binary content, base64-encoded (instead of text)",
247
+ },
248
+ contentType: { type: "string" },
249
+ ifVersion: { type: "integer" },
250
+ },
251
+ required: ["path"],
252
+ },
253
+ },
254
+ call: guarded(async (args) => {
255
+ const text = str(args.text);
256
+ const base64 = str(args.base64);
257
+ if ((text === undefined) === (base64 === undefined))
258
+ throw new Error("Provide exactly one of text or base64");
259
+ if (
260
+ base64 !== undefined &&
261
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(
262
+ base64,
263
+ )
264
+ )
265
+ throw new Error("Invalid base64 file content");
266
+ const content =
267
+ str(args.text) !== undefined
268
+ ? (str(args.text) as string)
269
+ : new Uint8Array(Buffer.from(str(args.base64) ?? "", "base64"));
270
+ const size =
271
+ typeof content === "string"
272
+ ? Buffer.byteLength(content)
273
+ : content.byteLength;
274
+ if (
275
+ features.storeUploadMaxBytes !== undefined &&
276
+ size > features.storeUploadMaxBytes
277
+ ) {
278
+ throw new Error(
279
+ `Document exceeds this server's limit of ${Math.floor(features.storeUploadMaxBytes / 1024 / 1024)}MB`,
280
+ );
281
+ }
282
+ return documents.write({
283
+ identity,
284
+ projectId,
285
+ path: str(args.path) ?? "",
286
+ content,
287
+ ...(str(args.contentType)
288
+ ? { contentType: str(args.contentType) }
289
+ : {}),
290
+ ...(int(args.ifVersion) !== undefined
291
+ ? { ifVersion: int(args.ifVersion) }
292
+ : {}),
293
+ });
294
+ }),
295
+ },
296
+ {
297
+ definition: {
298
+ name: "documents_delete",
299
+ description:
300
+ "Delete a store document (a tombstone version; history stays readable).",
301
+ inputSchema: {
302
+ type: "object",
303
+ properties: {
304
+ path: { type: "string" },
305
+ ifVersion: { type: "integer" },
306
+ },
307
+ required: ["path"],
308
+ },
309
+ annotations: { destructiveHint: true },
310
+ },
311
+ call: guarded(async (args) =>
312
+ documents.delete({
313
+ identity,
314
+ projectId,
315
+ path: str(args.path) ?? "",
316
+ ...(int(args.ifVersion) !== undefined
317
+ ? { ifVersion: int(args.ifVersion) }
318
+ : {}),
319
+ }),
320
+ ),
321
+ },
322
+ {
323
+ definition: {
324
+ name: "documents_history",
325
+ description:
326
+ "A store document's versions, newest first, with who wrote each.",
327
+ inputSchema: {
328
+ type: "object",
329
+ properties: { path: { type: "string" } },
330
+ required: ["path"],
331
+ },
332
+ annotations: READ_ONLY,
333
+ },
334
+ call: guarded(async (args) =>
335
+ documents.history({
336
+ identity,
337
+ projectId,
338
+ path: str(args.path) ?? "",
339
+ }),
340
+ ),
341
+ },
342
+ );
343
+ }
344
+
345
+ if (core.skills && mayUseProject(identity, projectId)) {
346
+ const skills = core.skills;
347
+ tools.push(
348
+ {
349
+ definition: {
350
+ name: "list_skills",
351
+ description:
352
+ "List the project's skills (how-to guides for working in this project) and the host's, by name with a one-line description.",
353
+ inputSchema: { type: "object", properties: {} },
354
+ annotations: READ_ONLY,
355
+ },
356
+ call: guarded(async () =>
357
+ (await skills.listShared(identity, projectId)).map((skill) => ({
358
+ name: skill.name,
359
+ title: skill.title,
360
+ description: skill.description,
361
+ source: skill.source,
362
+ })),
363
+ ),
364
+ },
365
+ {
366
+ definition: {
367
+ name: "read_skill",
368
+ description: "Read a skill's full SKILL.md by name.",
369
+ inputSchema: {
370
+ type: "object",
371
+ properties: { name: { type: "string" } },
372
+ required: ["name"],
373
+ },
374
+ annotations: READ_ONLY,
375
+ },
376
+ call: guarded(async (args) => {
377
+ const found = await skills.readShared(
378
+ identity,
379
+ projectId,
380
+ str(args.name) ?? "",
381
+ );
382
+ if (!found) throw new Error(`No skill named '${String(args.name)}'`);
383
+ return { ...found.skill, content: found.content };
384
+ }),
385
+ },
386
+ );
387
+ }
388
+
389
+ if (core.publications && features.publications !== false) {
390
+ const publications = core.publications;
391
+ const publicAllowed = features.publications === "public";
392
+ tools.push(
393
+ {
394
+ definition: {
395
+ name: "publish_document",
396
+ description:
397
+ "Share a document by URL. audience=members: anyone who may use this project, behind the host's login; audience=public: anyone with the link (anonymous, that one document only). Builders publish anything they can read; members only store documents they may write. Returns the URL path (relative to the host's API base) and the slug to revoke with.",
398
+ inputSchema: {
399
+ type: "object",
400
+ properties: {
401
+ path: { type: "string" },
402
+ audience: { type: "string", enum: ["public", "members"] },
403
+ slug: { type: "string", description: "Optional readable handle" },
404
+ },
405
+ required: ["path", "audience"],
406
+ },
407
+ },
408
+ call: guarded(async (args) => {
409
+ const audience = args.audience === "public" ? "public" : "members";
410
+ if (audience === "public" && !publicAllowed) {
411
+ throw new Error(
412
+ "Public links are turned off on this server; publish to members instead.",
413
+ );
414
+ }
415
+ const publication = await publications.publish({
416
+ identity,
417
+ projectId,
418
+ path: str(args.path) ?? "",
419
+ audience,
420
+ ...(str(args.slug) ? { slug: str(args.slug) } : {}),
421
+ });
422
+ return {
423
+ ...publication,
424
+ url:
425
+ audience === "public"
426
+ ? `/public/${projectId}/${publication.slug}`
427
+ : `/projects/${projectId}/publications/${publication.slug}`,
428
+ };
429
+ }),
430
+ },
431
+ {
432
+ definition: {
433
+ name: "revoke_publication",
434
+ description:
435
+ "Revoke a shared URL by slug; the link stops working immediately.",
436
+ inputSchema: {
437
+ type: "object",
438
+ properties: { slug: { type: "string" } },
439
+ required: ["slug"],
440
+ },
441
+ annotations: { destructiveHint: true },
442
+ },
443
+ call: guarded(async (args) => {
444
+ await publications.revoke({
445
+ identity,
446
+ projectId,
447
+ slug: str(args.slug) ?? "",
448
+ });
449
+ return { revoked: true };
450
+ }),
451
+ },
452
+ {
453
+ definition: {
454
+ name: "list_publications",
455
+ description:
456
+ "The shared URLs you may see (all of the project's with publications:read; otherwise your own).",
457
+ inputSchema: { type: "object", properties: {} },
458
+ annotations: READ_ONLY,
459
+ },
460
+ call: guarded(async () => publications.list({ identity, projectId })),
461
+ },
462
+ );
463
+ }
464
+
465
+ if (
466
+ core.proposals &&
467
+ features.proposals &&
468
+ mayUseProject(identity, projectId)
469
+ ) {
470
+ const proposals = core.proposals;
471
+ tools.push({
472
+ definition: {
473
+ name: "propose_change",
474
+ description:
475
+ "Propose a change to the program — docs, templates, workflows, anything outside store/ — when you cannot commit directly. The files land on a branch from the shared main authored as the caller, and a pull request opens on the caller's behalf when the project is linked to a code host. Give a clear title and, for each change, the full new content (or delete: true).",
476
+ inputSchema: {
477
+ type: "object",
478
+ properties: {
479
+ title: { type: "string" },
480
+ body: { type: "string" },
481
+ changes: {
482
+ type: "array",
483
+ items: {
484
+ type: "object",
485
+ properties: {
486
+ path: { type: "string" },
487
+ content: { type: "string" },
488
+ delete: { type: "boolean" },
489
+ },
490
+ required: ["path"],
491
+ },
492
+ },
493
+ },
494
+ required: ["title", "changes"],
495
+ },
496
+ },
497
+ call: guarded(async (args) => {
498
+ const changes = Array.isArray(args.changes)
499
+ ? (args.changes as Array<Record<string, unknown>>)
500
+ : [];
501
+ return proposals.propose({
502
+ identity,
503
+ projectId,
504
+ title: str(args.title) ?? "",
505
+ ...(str(args.body) ? { body: str(args.body) } : {}),
506
+ changes: changes.map((change) => ({
507
+ path: str(change.path) ?? "",
508
+ ...(typeof change.content === "string"
509
+ ? { content: change.content }
510
+ : {}),
511
+ ...(change.delete === true ? { delete: true } : {}),
512
+ })),
513
+ });
514
+ }),
515
+ });
516
+ }
517
+
518
+ if (core.agentSessions) {
519
+ const sessions = core.agentSessions;
520
+ const agentNames = (identity.scope ?? [])
521
+ .filter((ref) => ref.kind === "agent" && ref.projectId === projectId)
522
+ .map((ref) => (ref as { name: string }).name);
523
+ const hint =
524
+ agentNames.includes(EVERY_ARTIFACT) || identity.scope === undefined
525
+ ? "any committed project agent (.work/agents/<slug>.json)"
526
+ : agentNames.length > 0
527
+ ? `one of: ${agentNames.join(", ")}`
528
+ : "none available to you";
529
+ tools.push({
530
+ definition: {
531
+ name: "ask_agent",
532
+ description: `Ask one of the project's agents (${hint}) and get its reply — a full turn with the agent's own tools and persona. Pass sessionId to continue an earlier conversation, or environment to choose where a new one runs.`,
533
+ inputSchema: {
534
+ type: "object",
535
+ properties: {
536
+ agent: { type: "string", description: "The agent's slug" },
537
+ message: { type: "string" },
538
+ sessionId: { type: "string" },
539
+ environment: {
540
+ type: "string",
541
+ description:
542
+ "Environment for a new conversation (project_overview lists yours)",
543
+ },
544
+ },
545
+ required: ["agent", "message"],
546
+ },
547
+ },
548
+ call: guarded(async (args) => {
549
+ const agent = str(args.agent);
550
+ const message = str(args.message);
551
+ if (!agent || !message)
552
+ throw new Error("agent and message are required");
553
+ const agentId = projectAgentId(projectId, agent);
554
+ const sessionId =
555
+ str(args.sessionId) ??
556
+ (
557
+ await sessions.create(identity, projectId, {
558
+ agentId,
559
+ source: "mcp",
560
+ ...(str(args.environment)
561
+ ? { environment: str(args.environment) }
562
+ : {}),
563
+ })
564
+ ).id;
565
+ // Never the person's own words (ADR 0217): an agent's in Work, or
566
+ // the person's own assistant asking through this server.
567
+ const from = currentSessionId
568
+ ? {
569
+ kind: "agent" as const,
570
+ sessionId: currentSessionId,
571
+ agentId: (
572
+ await sessions.get(identity, projectId, currentSessionId)
573
+ ).agentId,
574
+ }
575
+ : {
576
+ kind: "assistant" as const,
577
+ externalUserId: identity.externalUserId,
578
+ };
579
+ try {
580
+ const { reply } = await sessions.sendMessage(
581
+ identity,
582
+ projectId,
583
+ sessionId,
584
+ message,
585
+ { from },
586
+ );
587
+ return {
588
+ sessionId,
589
+ reply: reply?.kind === "assistant_message" ? reply.text : "",
590
+ };
591
+ } catch (error) {
592
+ // No reply yet: the message waits for a machine, is held or
593
+ // cancelled, or its machine stopped. The caller reads the chat.
594
+ if (error instanceof AgentTurnUnsettledError)
595
+ return { sessionId, state: error.state, reply: error.message };
596
+ throw error;
597
+ }
598
+ }),
599
+ });
600
+
601
+ // A key of the calling chat's metadata (ADR 0226): bound to the
602
+ // session this connection serves, so there is none without one.
603
+ if (currentSessionId) {
604
+ const sessionId = currentSessionId;
605
+ tools.push({
606
+ definition: {
607
+ name: "set_session_metadata",
608
+ description: SET_SESSION_METADATA_DESCRIPTION,
609
+ inputSchema: z.toJSONSchema(setSessionMetadataInputSchema),
610
+ },
611
+ call: guarded(async (args) => {
612
+ const values = sessionMetadataToolWrite(args);
613
+ return {
614
+ metadata: values
615
+ ? await sessions.setMetadata({
616
+ identity,
617
+ projectId,
618
+ sessionId,
619
+ values,
620
+ })
621
+ : await sessions.metadata({ identity, projectId, sessionId }),
622
+ };
623
+ }),
624
+ });
625
+ }
626
+
627
+ tools.push({
628
+ definition: {
629
+ name: "send_agent_message",
630
+ description:
631
+ "Deliver an attributed message from your current session to this or another agent session. queue (the default) wakes an idle session or runs after its active turn; steer adds it to the active turn so the agent sees it while it works; interrupt stops the active turn and runs this next; message_only records it without waking the agent. Set attention to required to alert the user to this message, independently of whether the agent should run. Use interrupt only when delay would make the work wrong.",
632
+ inputSchema: {
633
+ type: "object",
634
+ properties: {
635
+ fromSessionId: { type: "string" },
636
+ toSessionId: { type: "string" },
637
+ message: { type: "string" },
638
+ mode: {
639
+ type: "string",
640
+ enum: ["queue", "steer", "interrupt", "message_only"],
641
+ default: "queue",
642
+ },
643
+ attention: { type: "string", enum: ["none", "required"] },
644
+ idempotencyKey: { type: "string" },
645
+ workspace: {
646
+ type: "object",
647
+ description:
648
+ "Move the receiving session's workspace to a ref of the project's linked remote before its next turn (a branch, tag, commit, or refs/pull/<n>/head). update: rebase (default) keeps its commits, reset discards them.",
649
+ properties: {
650
+ ref: { type: "string" },
651
+ update: { type: "string", enum: ["reset", "rebase"] },
652
+ },
653
+ required: ["ref"],
654
+ additionalProperties: false,
655
+ },
656
+ },
657
+ required: ["toSessionId", "message"],
658
+ },
659
+ },
660
+ call: guarded(async (args) => {
661
+ const fromSessionId = str(args.fromSessionId) ?? currentSessionId;
662
+ const toSessionId = str(args.toSessionId);
663
+ const message = str(args.message);
664
+ const mode = args.mode === undefined ? "queue" : args.mode;
665
+ if (
666
+ !fromSessionId ||
667
+ !toSessionId ||
668
+ !message ||
669
+ (mode !== "queue" &&
670
+ mode !== "steer" &&
671
+ mode !== "interrupt" &&
672
+ mode !== "message_only")
673
+ ) {
674
+ throw new Error(
675
+ "fromSessionId, toSessionId, message, and a valid mode are required",
676
+ );
677
+ }
678
+ if (
679
+ args.attention !== undefined &&
680
+ args.attention !== "none" &&
681
+ args.attention !== "required"
682
+ )
683
+ throw new Error("attention must be none or required");
684
+ const source = await sessions.get(identity, projectId, fromSessionId);
685
+ return sessions.deliver(identity, projectId, toSessionId, {
686
+ content: message,
687
+ author: {
688
+ kind: "agent",
689
+ sessionId: fromSessionId,
690
+ agentId: source.agentId,
691
+ },
692
+ mode,
693
+ attention: args.attention,
694
+ ...(str(args.idempotencyKey)
695
+ ? { idempotencyKey: str(args.idempotencyKey) }
696
+ : {}),
697
+ ...(args.workspace === undefined
698
+ ? {}
699
+ : { workspace: parseWorkspaceRequest(args.workspace) }),
700
+ });
701
+ }),
702
+ });
703
+
704
+ if (core.sessionActions) {
705
+ const actions = core.sessionActions;
706
+ for (const operation of Object.keys(
707
+ SESSION_ACTION_SCHEMAS,
708
+ ) as SessionActionOperation[]) {
709
+ tools.push({
710
+ definition: {
711
+ name: `session_${operation}`,
712
+ description: `Session ${operation}. Uses the same authorized operation as workflows. Name the chat by sessionId, or by the project's key for it (key, with audience "project" for the project chat). Mutations require a stable idempotencyKey; retries return the existing result. Load the session-workflows skill for examples.`,
713
+ inputSchema: z.toJSONSchema(SESSION_ACTION_SCHEMAS[operation]),
714
+ },
715
+ call: guarded(async (args) => {
716
+ const source = currentSessionId
717
+ ? await sessions.get(identity, projectId, currentSessionId)
718
+ : undefined;
719
+ return actions.execute({
720
+ identity,
721
+ projectId,
722
+ operation,
723
+ args,
724
+ author: source
725
+ ? {
726
+ kind: "agent",
727
+ sessionId: source.id,
728
+ agentId: source.agentId,
729
+ }
730
+ : { kind: "user", externalUserId: identity.externalUserId },
731
+ causation: source
732
+ ? await sessions.causalContext({
733
+ identity,
734
+ projectId,
735
+ sessionId: source.id,
736
+ })
737
+ : [],
738
+ });
739
+ }),
740
+ });
741
+ }
742
+ }
743
+
744
+ if (core.watchers) {
745
+ const watchers = core.watchers;
746
+ const eventSources = core.projectEventSources.map(
747
+ (source) => source.kind,
748
+ );
749
+ tools.push(
750
+ {
751
+ definition: {
752
+ name: "create_watcher",
753
+ description: `Temporarily enable an ordinary TypeScript workflow owned by this session. To repeat a shell check (a URL, a file, a CLI), use the host's watch_command when it is offered: it runs where your commands run. For periodic monitoring with workflow IO, declare a normal schedule trigger. For event-driven work, use normalized Project Events already supplied by this host. Stop, expiry, or session close/archive disables future invocations. The source must export the named defineWorkflow and declare one or more inline triggers, for example triggers: [trigger("issue.changed")]. Event triggers receive the normalized Project Event envelope; schedule triggers receive their normal scheduled payload. To notify or wake a session, return context.host["catamorphic.sessions"].deliver({ sessionId, content, mode, idempotencyKey }) from a boundary. Pass source directly; do not write it to the user working tree. The host places it at .work/workflows/src/artifacts/<id>.ts in an isolated committed-origin checkout, so imports must already exist in that origin. workflowName must be exported by this source. The workflow is committed to an isolated work/artifacts/<id> ref, pinned, and never merged into project main. This is temporary execution, not private storage. Call stop_watcher when the task is complete. Load the workflow-lifecycle skill for lifetime and publishing guidance.${
754
+ eventSources.length
755
+ ? ` This host can also observe outside systems that cannot reach it with a webhook: pass eventSource (${eventSources.join(", ")}) and the host polls for new events from now on and records them as Project Events shaped like the webhook deliveries the source replaces, so bind the project's trigger kinds for that webhook (for example from .work/triggers/).`
756
+ : ""
757
+ }`,
758
+ inputSchema: {
759
+ type: "object",
760
+ properties: {
761
+ sessionId: { type: "string" },
762
+ workflowName: { type: "string" },
763
+ source: {
764
+ type: "string",
765
+ description:
766
+ "TypeScript source exporting workflowName; no Markdown fences. It runs from .work/workflows/src/artifacts/<id>.ts against the committed project origin.",
767
+ },
768
+ environment: { type: "string" },
769
+ expiresInSeconds: {
770
+ type: "integer",
771
+ minimum: 1,
772
+ description:
773
+ "Optional expiry in seconds. Omit for reminders that must survive offline time. Defaults to no expiry; completion, stop, or archive ends execution.",
774
+ },
775
+ ...(eventSources.length
776
+ ? {
777
+ eventSource: {
778
+ type: "string",
779
+ enum: eventSources,
780
+ description:
781
+ "A host event source to poll for this watcher, from now on.",
782
+ },
783
+ pollIntervalSeconds: { type: "integer", minimum: 5 },
784
+ }
785
+ : {}),
786
+ },
787
+ required: ["workflowName", "source"],
788
+ },
789
+ },
790
+ call: guarded(async (args) => {
791
+ const sessionId = str(args.sessionId) ?? currentSessionId;
792
+ const workflowName = str(args.workflowName);
793
+ const source = str(args.source);
794
+ if (!sessionId || !workflowName || !source) {
795
+ throw new Error(
796
+ "sessionId, workflowName, and source are required",
797
+ );
798
+ }
799
+ const eventSource = str(args.eventSource);
800
+ const pollIntervalSeconds = int(args.pollIntervalSeconds);
801
+ return watchers.create({
802
+ identity,
803
+ projectId,
804
+ sessionId,
805
+ workflowName,
806
+ source,
807
+ ...(str(args.environment)
808
+ ? { environment: str(args.environment) }
809
+ : {}),
810
+ ...(int(args.expiresInSeconds) !== undefined
811
+ ? { expiresInSeconds: int(args.expiresInSeconds) }
812
+ : {}),
813
+ ...(eventSource
814
+ ? {
815
+ eventSource: {
816
+ kind: eventSource,
817
+ ...(pollIntervalSeconds !== undefined
818
+ ? { pollIntervalSeconds }
819
+ : {}),
820
+ },
821
+ }
822
+ : {}),
823
+ });
824
+ }),
825
+ },
826
+ {
827
+ definition: {
828
+ name: "list_watchers",
829
+ description:
830
+ "List temporary watchers owned by the current session, including pinned commit, expiry, status, and last error.",
831
+ inputSchema: {
832
+ type: "object",
833
+ properties: { sessionId: { type: "string" } },
834
+ },
835
+ annotations: READ_ONLY,
836
+ },
837
+ call: guarded(async (args) => {
838
+ const sessionId = str(args.sessionId) ?? currentSessionId;
839
+ if (!sessionId) throw new Error("sessionId is required");
840
+ return watchers.list({
841
+ identity,
842
+ projectId,
843
+ sessionId,
844
+ });
845
+ }),
846
+ },
847
+ {
848
+ definition: {
849
+ name: "stop_watcher",
850
+ description: "Stop a temporary watcher owned by a session.",
851
+ inputSchema: {
852
+ type: "object",
853
+ properties: {
854
+ sessionId: { type: "string" },
855
+ watcherId: { type: "string" },
856
+ },
857
+ required: ["watcherId"],
858
+ },
859
+ },
860
+ call: guarded(async (args) => {
861
+ const sessionId = str(args.sessionId) ?? currentSessionId;
862
+ const watcherId = str(args.watcherId);
863
+ if (!sessionId || !watcherId) {
864
+ throw new Error("sessionId and watcherId are required");
865
+ }
866
+ return {
867
+ stopped: await watchers.stop({
868
+ identity,
869
+ projectId,
870
+ sessionId,
871
+ watcherId,
872
+ }),
873
+ };
874
+ }),
875
+ },
876
+ );
877
+ }
878
+ }
879
+
880
+ return tools;
881
+ }