@ultimat3/mcp 29.4.0 → 30.1.0

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 (63) hide show
  1. package/CLAUDE.md +54 -59
  2. package/README.md +259 -2
  3. package/package.json +21 -10
  4. package/src/app-catalog.ts +84 -0
  5. package/src/app-tool.ts +6 -2
  6. package/src/app-tools.ts +80 -5
  7. package/src/audit-hook.ts +7 -1
  8. package/src/audit.ts +12 -1
  9. package/src/catalog-errors.ts +97 -0
  10. package/src/confirmation-approvers.ts +85 -0
  11. package/src/confirmation-decide.ts +78 -8
  12. package/src/confirmation-evidence.ts +118 -0
  13. package/src/confirmation-gate.ts +147 -44
  14. package/src/confirmation-postgres.ts +88 -7
  15. package/src/confirmation-quorum-errors.ts +102 -0
  16. package/src/confirmation-schema.ts +13 -2
  17. package/src/confirmation-store.ts +54 -19
  18. package/src/confirmations.ts +77 -8
  19. package/src/dev-graph-tool.ts +62 -0
  20. package/src/dev-server.ts +10 -2
  21. package/src/errors-transport.ts +84 -3
  22. package/src/errors.ts +46 -0
  23. package/src/exposed.ts +13 -3
  24. package/src/framework-error.ts +8 -1
  25. package/src/from-action.ts +2 -3
  26. package/src/index.ts +102 -1
  27. package/src/job-status-tool.ts +66 -0
  28. package/src/job-tool-errors.ts +15 -0
  29. package/src/job-tool.ts +167 -0
  30. package/src/oauth-metadata.ts +2 -2
  31. package/src/oauth-server.ts +80 -0
  32. package/src/projectable.ts +15 -10
  33. package/src/protocol-era.ts +270 -0
  34. package/src/recipe-errors.ts +75 -0
  35. package/src/recipe-links.ts +49 -0
  36. package/src/recipe-markdown.ts +143 -0
  37. package/src/recipe-replay.ts +101 -0
  38. package/src/recipe-search.ts +82 -0
  39. package/src/recipes-surface.ts +55 -0
  40. package/src/recipes-tool.ts +123 -0
  41. package/src/recipes.ts +167 -0
  42. package/src/registry.ts +5 -0
  43. package/src/remote-client.ts +378 -0
  44. package/src/remote-errors.ts +76 -0
  45. package/src/remote-listen.ts +108 -0
  46. package/src/remote-lock.ts +139 -0
  47. package/src/remote-oauth.ts +258 -0
  48. package/src/remote-schema.ts +51 -0
  49. package/src/remote-tools.ts +157 -0
  50. package/src/remote-wire.ts +121 -0
  51. package/src/resources.ts +84 -13
  52. package/src/runtime-schema.ts +132 -0
  53. package/src/runtime-tool.ts +115 -0
  54. package/src/scopes.ts +8 -1
  55. package/src/server-catalog.ts +200 -0
  56. package/src/server-resources.ts +117 -0
  57. package/src/server-voice.ts +10 -5
  58. package/src/server.ts +149 -168
  59. package/src/tenant.ts +189 -0
  60. package/src/transport-http-answers.ts +124 -0
  61. package/src/transport-http.ts +50 -94
  62. package/src/wire.ts +18 -4
  63. package/src/caller-context.ts +0 -22
package/src/index.ts CHANGED
@@ -6,6 +6,7 @@ export type { RequestFacts as McpRequestFacts } from '@ultimat3/http';
6
6
  /** Re-exported so a `defineAppMcp` file needs one import, not two. Same object as schema's. */
7
7
  export type { Infer } from '@ultimat3/schema';
8
8
  export { t } from '@ultimat3/schema';
9
+ export type { McpCatalog, McpRuntimeCatalog } from './app-catalog';
9
10
  export type {
10
11
  AnyAppToolDefinition,
11
12
  AppToolArgs,
@@ -24,6 +25,20 @@ export type {
24
25
  McpAuthRefusal,
25
26
  } from './audit-hook';
26
27
  export { mcpAuditor } from './audit-hook';
28
+ export type { McpCatalogNameSource } from './catalog-errors';
29
+ export {
30
+ McpCatalogToolDuplicateError,
31
+ McpCatalogUnresolvedError,
32
+ McpTenantInvalidError,
33
+ McpTenantRequiredError,
34
+ McpTenantUnresolvedError,
35
+ } from './catalog-errors';
36
+ export type {
37
+ McpApproverSelector,
38
+ McpApproversCall,
39
+ McpApproversResolver,
40
+ McpConfirmationApprovers,
41
+ } from './confirmation-approvers';
27
42
  export {
28
43
  McpConfirmationArgumentsMismatchError,
29
44
  McpConfirmationContestedError,
@@ -34,6 +49,17 @@ export {
34
49
  McpConfirmationToolUnknownError,
35
50
  McpConfirmationUnknownError,
36
51
  } from './confirmation-errors';
52
+ export type {
53
+ McpConfirmationEvidence,
54
+ McpConfirmationVerdict,
55
+ McpEvidenceCheck,
56
+ VerifyConfirmationOptions,
57
+ } from './confirmation-evidence';
58
+ export {
59
+ confirmationSigningPayload,
60
+ MCP_CONFIRMATION_SIGNING_PURPOSE,
61
+ verifyConfirmationEvidence,
62
+ } from './confirmation-evidence';
37
63
  export {
38
64
  inputDigest,
39
65
  MCP_CONFIRMATION_ARGUMENTS_PURPOSE,
@@ -42,9 +68,16 @@ export {
42
68
  } from './confirmation-gate';
43
69
  export type { PostgresConfirmationStoreOptions } from './confirmation-postgres';
44
70
  export { postgresConfirmationStore } from './confirmation-postgres';
71
+ export type { McpEvidenceFailure } from './confirmation-quorum-errors';
72
+ export {
73
+ McpConfirmationEvidenceInvalidError,
74
+ McpConfirmationQuorumInvalidError,
75
+ McpConfirmationQuorumPendingError,
76
+ } from './confirmation-quorum-errors';
45
77
  // The confirmation table's DDL is `@ultimat3/mcp/schema`'s alone — one import path for one statement.
46
78
  export type {
47
79
  McpConfirmation,
80
+ McpConfirmationApproval,
48
81
  McpConfirmationDraft,
49
82
  McpConfirmationStatus,
50
83
  McpConfirmationStore,
@@ -56,6 +89,8 @@ export type {
56
89
  McpConfirmationsInput,
57
90
  } from './confirmations';
58
91
  export { DEFAULT_MCP_CONFIRMATION_TTL_MS, mcpConfirmations } from './confirmations';
92
+ export type { DevGraphHost, DevGraphQuestion } from './dev-graph-tool';
93
+ export { graphQuestion } from './dev-graph-tool';
59
94
  export type { DevMcpServerInput } from './dev-host';
60
95
  export { devHost, devMcpServer, frameworkIntrospection } from './dev-host';
61
96
  export type {
@@ -119,15 +154,23 @@ export {
119
154
  McpToolUnknownError,
120
155
  McpToolUnsafeError,
121
156
  } from './errors';
157
+ export type { McpMirroredHeader } from './errors-transport';
122
158
  export {
123
159
  McpBodyTooLargeError,
160
+ McpHeaderMismatchError,
161
+ McpHostRefusedError,
124
162
  McpOAuthInvalidError,
163
+ McpOriginRefusedError,
164
+ McpProtocolUnsupportedError,
125
165
  McpRateLimitedError,
126
166
  } from './errors-transport';
127
167
  export { exposedPrimitives } from './exposed';
128
168
  export type { ProjectablePrimitive } from './from-action';
129
169
  export { deriveAnnotations, toolFrom, toolsFrom, toolsListed } from './from-action';
130
170
  export { MCP_IDEMPOTENCY_KEY_ARG } from './idempotency-arg';
171
+ export type { JobToolAnswer, JobToolDef, JobToolWait } from './job-tool';
172
+ export { JOB_STATUS_TOOL, JOB_TOOL_INLINE_CEILING_MS, jobTool } from './job-tool';
173
+ export { McpJobToolInvalidError } from './job-tool-errors';
131
174
  export type { ListFilterOp, McpListParams } from './list-params';
132
175
  export { DEFAULT_LIST_MAX_LIMIT, listParamsSchema } from './list-params';
133
176
  export {
@@ -175,6 +218,8 @@ export {
175
218
  PROTECTED_RESOURCE_WELL_KNOWN,
176
219
  protectedResourceMetadata,
177
220
  } from './oauth-metadata';
221
+ export type { McpAuthorizationServer, McpAuthorizationServerOptions } from './oauth-server';
222
+ export { mcpAuthorizationServer } from './oauth-server';
178
223
  export type { ListedPrimitive } from './projectable';
179
224
  export { asProjectable, toRowsOutputSchema } from './projectable';
180
225
  export type { QueryLimits, QueryResult, QueryRows } from './query-limits';
@@ -184,6 +229,21 @@ export {
184
229
  } from './query-limits';
185
230
  export type { DatabaseTarget } from './readonly-sql';
186
231
  export { assertBranchDatabase, assertReadOnlyQuery } from './readonly-sql';
232
+ export {
233
+ McpRecipeExampleInvalidError,
234
+ McpRecipeLinkDanglingError,
235
+ McpRecipeToolUnknownError,
236
+ McpRecipeUnknownError,
237
+ McpRecipeUriReservedError,
238
+ } from './recipe-errors';
239
+ export { assertRecipeLinks, servedRecipes } from './recipe-links';
240
+ export { markdownRecipes, recipeFromMarkdown } from './recipe-markdown';
241
+ export type { ReplayOptions, ReplayReport } from './recipe-replay';
242
+ export { replayRecipes } from './recipe-replay';
243
+ export type { McpRecipe, McpRecipeStep } from './recipes';
244
+ export { RECIPE_URI_PREFIX, recipeUri, renderRecipe } from './recipes';
245
+ export type { ExtraRecipes } from './recipes-tool';
246
+ export { DOCS_TOOL } from './recipes-tool';
187
247
  export type {
188
248
  AnyMcpTool,
189
249
  ContentBlock,
@@ -206,11 +266,43 @@ export {
206
266
  toolListEntry,
207
267
  visibleToCaller,
208
268
  } from './registry';
269
+ export type {
270
+ McpClient,
271
+ McpClientOptions,
272
+ RemoteTool,
273
+ RemoteToolResult,
274
+ } from './remote-client';
275
+ export { mcpClient } from './remote-client';
276
+ export type { McpRemoteFailure } from './remote-errors';
277
+ export {
278
+ McpRemoteAuthRequiredError,
279
+ McpRemoteRefusedError,
280
+ McpRemoteToolChangedError,
281
+ } from './remote-errors';
282
+ export type { LockedServer, LockedTool } from './remote-lock';
283
+ export {
284
+ assertLocked,
285
+ lockChanges,
286
+ readToolsLock,
287
+ TOOLS_LOCK_FILE,
288
+ writeToolsLock,
289
+ } from './remote-lock';
290
+ export type {
291
+ McpOAuthClient,
292
+ McpOAuthClientOptions,
293
+ McpOAuthHandshake,
294
+ McpOAuthStart,
295
+ McpOAuthTokens,
296
+ } from './remote-oauth';
297
+ export { mcpOAuthClient } from './remote-oauth';
298
+ export type { DeclaredMcpServer, McpTools, McpToolsDef, RemoteToolAction } from './remote-tools';
299
+ export { declaredMcpServers, mcpTools, RemoteToolOutput } from './remote-tools';
209
300
  export type {
210
301
  FrameworkResourceProviders,
211
302
  McpPrompt,
212
303
  McpPromptArgument,
213
304
  McpResource,
305
+ McpResourceSource,
214
306
  ResourceContents,
215
307
  ResourceListEntry,
216
308
  ResourceResolution,
@@ -222,13 +314,18 @@ export {
222
314
  ResourceRegistry,
223
315
  toPrompts,
224
316
  } from './resources';
317
+ export type { McpRuntimeTool, RuntimeToolArgs, RuntimeToolDefinition } from './runtime-tool';
318
+ export { runtimeTool } from './runtime-tool';
225
319
  export type { McpScopes } from './scopes';
226
320
  export { withScopes } from './scopes';
227
321
  export type { McpServer, McpServerInput, McpWire } from './server';
228
322
  export { mcpServer } from './server';
323
+ export type { McpCatalogSource, McpResolvedCatalog } from './server-catalog';
229
324
  export type { McpInstructions, McpServerVoice } from './server-voice';
230
325
  export type { McpSurfaceBudget, McpSurfaceSize } from './surface-budget';
231
326
  export { assertMcpSurfaceBudget, measureMcpSurface } from './surface-budget';
327
+ export type { McpTenant, McpTenantEntry } from './tenant';
328
+ export { LIST_TENANTS } from './tenant';
232
329
  export type {
233
330
  McpHttpTransportInput,
234
331
  McpProtectedResource,
@@ -243,6 +340,7 @@ export {
243
340
  MCP_UNAUTHENTICATED_LIMIT,
244
341
  mcpHttpRoute,
245
342
  } from './transport-http';
343
+ export { mcpHostRefused } from './transport-http-answers';
246
344
  export type { StdioTransportInput } from './transport-stdio';
247
345
  export { serveStdio } from './transport-stdio';
248
346
  export type { ArgIssue, ArgValidation } from './validate-args';
@@ -258,12 +356,15 @@ export type {
258
356
  export {
259
357
  defaultServerInfo,
260
358
  errorResponse,
359
+ HEADER_MISMATCH,
261
360
  INTERNAL_ERROR,
262
361
  INVALID_PARAMS,
263
362
  INVALID_REQUEST,
264
363
  isJsonRpcRequest,
265
- MCP_PROTOCOL_VERSION,
364
+ MCP_LEGACY_VERSIONS,
365
+ MCP_MODERN_VERSIONS,
266
366
  METHOD_NOT_FOUND,
267
367
  PARSE_ERROR,
268
368
  resultResponse,
369
+ UNSUPPORTED_PROTOCOL_VERSION,
269
370
  } from './wire';
@@ -0,0 +1,66 @@
1
+ /**
2
+ * `job_status` — the one read every `jobTool()` points at, projected once per server that declares
3
+ * any. Gated per ROW, as `whoami` is gated per caller: the caller must be the actor that enqueued
4
+ * it, in the same org. Anything else — another actor, another org, an id nobody issued, a job no
5
+ * tool of this server runs — is the SAME not-found, because `uuidV7` ids are time-ordered guesses.
6
+ */
7
+
8
+ import { asCallerContext, guardActionBeforeInput } from '@ultimat3/action';
9
+ import type { Actor } from '@ultimat3/core';
10
+ import { actorOf, useContext } from '@ultimat3/core';
11
+ import { JobNotFoundError } from '@ultimat3/jobs';
12
+ import { can } from '@ultimat3/policy';
13
+ import type { ProjectablePrimitive } from './from-action';
14
+ import type { JobToolBrand } from './job-tool';
15
+ import { introspection, JOB_STATUS_TOOL, running, settled } from './job-tool';
16
+
17
+ export function jobStatusPrimitive(brands: readonly JobToolBrand[]): ProjectablePrimitive {
18
+ const byJob = new Map(brands.map((brand) => [brand.job.name, brand]));
19
+ const description =
20
+ 'Read a long-running job this caller started: running, done with its result, or failed with its code and, when the error declares one, its callerFix.';
21
+ return {
22
+ name: JOB_STATUS_TOOL,
23
+ description,
24
+ mcp: { expose: true, description, annotations: { readOnlyHint: true } },
25
+ inputJsonSchema: {
26
+ type: 'object',
27
+ properties: { jobId: { type: 'string', description: 'The jobId a job tool answered.' } },
28
+ required: ['jobId'],
29
+ additionalProperties: false,
30
+ },
31
+ mutates: false,
32
+ run: ({ input, actor }) =>
33
+ asCallerContext(actor, async () => {
34
+ const jobId = readJobId(input);
35
+ const row = await introspection().job(jobId);
36
+ const brand = row === undefined ? undefined : byJob.get(row.name);
37
+ if (row === undefined || brand === undefined || !owns(row, actor)) {
38
+ throw new JobNotFoundError({ jobId, driver: 'jobs' });
39
+ }
40
+ // The tool's own permission still decides: a caller who lost it reads nothing more.
41
+ const ctx = useContext();
42
+ guardActionBeforeInput(
43
+ can(brand.policy),
44
+ { actor: actorOf(ctx), ctx, action: JOB_STATUS_TOOL },
45
+ 'mcp',
46
+ );
47
+ return (await settled(row, brand.result, brand.resultInput)) ?? running(row.id);
48
+ }),
49
+ };
50
+ }
51
+
52
+ /** The validated args carry a string `jobId`; anything else is the same not-found. */
53
+ function readJobId(input: unknown): string {
54
+ const jobId =
55
+ typeof input === 'object' && input !== null ? (input as { jobId?: unknown }).jobId : undefined;
56
+ return typeof jobId === 'string' ? jobId : '';
57
+ }
58
+
59
+ /** `enqueuedBy` is attribution for what a body may do; here it answers whose request this was. */
60
+ function owns(
61
+ row: { readonly enqueuedBy?: string; readonly tenantId?: string },
62
+ actor: Actor,
63
+ ): boolean {
64
+ if (row.enqueuedBy === undefined || row.enqueuedBy !== actor.id) return false;
65
+ return row.tenantId === undefined || row.tenantId === (actor.orgId ?? undefined);
66
+ }
@@ -0,0 +1,15 @@
1
+ // `jobTool()`'s one load refusal, `X_MCP_JOB_TOOL_INVALID`: something it was handed cannot be the
2
+ // durable, reportable long tool it promises — not a job handle, an `inlineMs` past what a client
3
+ // waits, or a jobs driver that cannot say how a job is doing.
4
+
5
+ import { UltimateError } from '@ultimat3/core';
6
+
7
+ export class McpJobToolInvalidError extends UltimateError {
8
+ constructor(input: { readonly reason: string }) {
9
+ super({
10
+ code: 'X_MCP_JOB_TOOL_INVALID',
11
+ cause: `jobTool() ${input.reason}`,
12
+ fix: "jobTool({ job: reindexJob, policy: 'catalog:admin', description, result: reindexStatus, inlineMs: 5_000 }) # job() handle, inlineMs 0..25000, postgres or memory jobs driver",
13
+ });
14
+ }
15
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * `jobTool()` — an MCP tool for work longer than a client waits: enqueue at once, wait up to
3
+ * `inlineMs`, then answer the app's `result` query as the caller, or `running` with the next call
4
+ * (`job_status`). A factory over a hand-written tool composing `job` and `query`.
5
+ */
6
+
7
+ import type { Ctx } from '@ultimat3/core';
8
+ import { useContext } from '@ultimat3/core';
9
+ import type { AnyJobHandle, JobIntrospection, JobRecord } from '@ultimat3/jobs';
10
+ import { callerFailure, isJobHandle, jobDriver } from '@ultimat3/jobs';
11
+ import type { KnownPermission } from '@ultimat3/policy';
12
+ import type { AnyQuery } from '@ultimat3/query';
13
+ import type { InferOutput, StandardSchemaV1 } from '@ultimat3/schema';
14
+ import type { AnyAppToolDefinition } from './app-tool';
15
+ import { McpJobToolInvalidError } from './job-tool-errors';
16
+
17
+ export const JOB_STATUS_TOOL = 'job_status';
18
+ export const JOB_TOOL_POLL_MS = 250;
19
+ export const JOB_TOOL_INLINE_MS = 5_000;
20
+ /** Past this an MCP client has usually given up: an answer it never reads is no answer. */
21
+ export const JOB_TOOL_INLINE_CEILING_MS = 25_000;
22
+
23
+ /** Waits `ms` or until `signal` aborts. The seam a test hands a frozen clock's `advance`. */
24
+ export type JobToolWait = (ms: number, signal: AbortSignal) => Promise<void>;
25
+
26
+ export interface JobToolDef<TInput extends StandardSchemaV1 = StandardSchemaV1> {
27
+ readonly job: AnyJobHandle;
28
+ readonly description: string;
29
+ /** Who may START it, and who may read its status — the same permission, the same gate. */
30
+ readonly policy: KnownPermission;
31
+ /** The tool's input. Default: the job's own input schema. */
32
+ readonly input?: TInput;
33
+ /**
34
+ * The job's input, from the tool's and the caller's request — a member id read off the caller,
35
+ * never a field an agent fills in. Default: the tool's input, unchanged.
36
+ */
37
+ readonly jobInput?: (input: InferOutput<TInput>, ctx: Ctx) => unknown;
38
+ /** Where the answer is read from, as the caller: the job writes where this query reads. */
39
+ readonly result: AnyQuery;
40
+ /** The `result` query's input. Default: the tool's input. */
41
+ readonly resultInput?: (input: unknown) => unknown;
42
+ /** How long to answer inline before `running`. Default 5,000 ms, at most 25,000. */
43
+ readonly inlineMs?: number;
44
+ readonly wait?: JobToolWait;
45
+ }
46
+
47
+ /** What `job_status` needs of a job tool, found again by the brand on its definition. */
48
+ export interface JobToolBrand {
49
+ readonly job: AnyJobHandle;
50
+ readonly result: AnyQuery;
51
+ readonly resultInput: (input: unknown) => unknown;
52
+ readonly policy: KnownPermission;
53
+ }
54
+
55
+ const BRANDS = new WeakMap<object, JobToolBrand>();
56
+
57
+ export const jobToolBrand = (def: object): JobToolBrand | undefined => BRANDS.get(def);
58
+
59
+ export type JobToolAnswer =
60
+ | { readonly status: 'done'; readonly jobId: string; readonly result: unknown }
61
+ | {
62
+ readonly status: 'running';
63
+ readonly jobId: string;
64
+ readonly poll: { readonly tool: string; readonly arguments: { readonly jobId: string } };
65
+ }
66
+ | {
67
+ readonly status: 'failed';
68
+ readonly jobId: string;
69
+ readonly code: string;
70
+ /** The thrown error's declared `callerFix`; absent when it declared none. */
71
+ readonly callerFix?: string;
72
+ };
73
+
74
+ export function jobTool<TInput extends StandardSchemaV1 = StandardSchemaV1>(
75
+ def: JobToolDef<TInput>,
76
+ ): AnyAppToolDefinition {
77
+ if (!isJobHandle(def.job)) {
78
+ throw new McpJobToolInvalidError({ reason: "was given a job that is not job()'s handle" });
79
+ }
80
+ const inlineMs = def.inlineMs ?? JOB_TOOL_INLINE_MS;
81
+ if (!Number.isSafeInteger(inlineMs) || inlineMs < 0 || inlineMs > JOB_TOOL_INLINE_CEILING_MS) {
82
+ throw new McpJobToolInvalidError({
83
+ reason: `was given inlineMs ${String(inlineMs)}; it must be a whole number of ms, 0 to ${String(JOB_TOOL_INLINE_CEILING_MS)}`,
84
+ });
85
+ }
86
+ const resultInput = def.resultInput ?? ((input: unknown) => input);
87
+ // `handle` is given `def.input` parsed — `TInput`'s output — so this widening restates no type.
88
+ const jobInput = (def.jobInput ?? ((input: unknown) => input)) as (
89
+ input: unknown,
90
+ ctx: Ctx,
91
+ ) => unknown;
92
+ const wait = def.wait ?? realWait;
93
+ // Bounded by polls as well as by the clock: a clock that does not move (a frozen test clock, a
94
+ // stalled monotonic source) must still end the wait, or the call never answers at all.
95
+ const polls = Math.ceil(inlineMs / JOB_TOOL_POLL_MS);
96
+ const tool: AnyAppToolDefinition = {
97
+ description: `${def.description} Long-running: answers inline when it can, else { status: 'running', poll } — call ${JOB_STATUS_TOOL} with that jobId.`,
98
+ input: def.input ?? def.job.input,
99
+ policy: def.policy,
100
+ destructive: true,
101
+ async handle({ input, ctx }) {
102
+ const introspect = introspection();
103
+ const queued = await def.job.as(ctx.actor, await jobInput(input, ctx));
104
+ const started = ctx.clock.monotonic();
105
+ for (let polled = 0; ; polled += 1) {
106
+ const row = await introspect.job(queued.id);
107
+ const answer = row === undefined ? undefined : await settled(row, def.result, resultInput);
108
+ if (answer !== undefined) return answer;
109
+ // A client that drops loses nothing: the job is queued, and `job_status` reads it later.
110
+ if (ctx.signal.aborted) return running(queued.id);
111
+ if (polled >= polls || ctx.clock.monotonic() - started >= inlineMs) {
112
+ return running(queued.id);
113
+ }
114
+ await wait(Math.min(JOB_TOOL_POLL_MS, inlineMs), ctx.signal);
115
+ }
116
+ },
117
+ };
118
+ BRANDS.set(tool, { job: def.job, result: def.result, resultInput, policy: def.policy });
119
+ return tool;
120
+ }
121
+
122
+ /** The driver's operator surface, or the refusal: a long tool that cannot report is not one. */
123
+ export function introspection(): JobIntrospection {
124
+ const introspect = jobDriver()?.introspect;
125
+ if (introspect === undefined) {
126
+ throw new McpJobToolInvalidError({
127
+ reason: 'needs a jobs driver with introspect, and the installed one has none',
128
+ });
129
+ }
130
+ return introspect;
131
+ }
132
+
133
+ export function running(jobId: string): JobToolAnswer {
134
+ return { status: 'running', jobId, poll: { tool: JOB_STATUS_TOOL, arguments: { jobId } } };
135
+ }
136
+
137
+ /**
138
+ * A finished row's answer, or `undefined` while it runs. `done` reads `result` AS THE CALLER (its
139
+ * own policy decides); `failed` carries the code and a declared `callerFix` alone — a row's text
140
+ * is the worker's, and its developer `fix` names what only the app's author can run.
141
+ */
142
+ export async function settled(
143
+ row: JobRecord,
144
+ result: AnyQuery,
145
+ resultInput: (input: unknown) => unknown,
146
+ ): Promise<JobToolAnswer | undefined> {
147
+ if (row.state === 'done') {
148
+ const caller = useContext().actor;
149
+ const rows = await result.as(caller, resultInput(row.input), { surface: 'mcp' });
150
+ return { status: 'done', jobId: row.id, result: rows };
151
+ }
152
+ if (row.state === 'failed' || row.state === 'dead' || row.state === 'cancelled') {
153
+ return { status: 'failed', jobId: row.id, ...callerFailure(row.lastError) };
154
+ }
155
+ return undefined;
156
+ }
157
+
158
+ const realWait: JobToolWait = (ms, signal) =>
159
+ new Promise<void>((resolve) => {
160
+ const timer = setTimeout(done, ms);
161
+ function done(): void {
162
+ clearTimeout(timer);
163
+ signal.removeEventListener('abort', done);
164
+ resolve();
165
+ }
166
+ signal.addEventListener('abort', done, { once: true });
167
+ });
@@ -1,8 +1,8 @@
1
1
  // OAuth 2.0 Protected Resource Metadata (RFC 9728) for the MCP endpoint — the framework half of
2
2
  // the MCP authorization spec (2025-06-18, unchanged in 2025-11-25): a 401 names where the metadata
3
3
  // lives (`WWW-Authenticate: Bearer resource_metadata="…"`), and the metadata names the
4
- // authorization server(s) a client goes to for a token. The authorization server itself is the
5
- // APP's — its consent page, its token endpoint, its revocation list — never this package's.
4
+ // authorization server(s) a client goes to for a token. The server itself is `@ultimat3/auth`'s
5
+ // `authorizationServer`, bound to one endpoint by `mcpAuthorizationServer` (`oauth-server.ts`).
6
6
 
7
7
  import { McpOAuthInvalidError } from './errors-transport';
8
8
 
@@ -0,0 +1,80 @@
1
+ // `mcpAuthorizationServer`: `@ultimat3/auth`'s `authorizationServer` bound to ONE MCP endpoint —
2
+ // every grant bound to its `resource` (RFC 8707), the `resolveToken` that refuses any other, the
3
+ // `oauth` block `defineAppMcp` advertises, and each decision as an `mcp.auth.*` line. No second
4
+ // implementation: every protocol rule is auth's; this file only binds and audits.
5
+
6
+ import {
7
+ type AuthorizationServer,
8
+ type AuthorizationServerOptions,
9
+ type AuthServerEvent,
10
+ authorizationServer,
11
+ oauthBearerResolver,
12
+ type ResolvedGrant,
13
+ } from '@ultimat3/auth';
14
+ import type { Actor, Logger } from '@ultimat3/core';
15
+ import { logger } from '@ultimat3/core';
16
+ import type { McpOAuth } from './oauth-metadata';
17
+ import type { ResolvedToken } from './transport-http';
18
+
19
+ export interface McpAuthorizationServerOptions
20
+ extends Omit<AuthorizationServerOptions, 'defaultResource'> {
21
+ /** The MCP endpoint's canonical URL, e.g. `https://www.example.com/mcp`. Every grant binds to it. */
22
+ readonly resource: string;
23
+ /** What a subject is NOW — built per call, so a removed member loses access with no sweep. */
24
+ readonly actor: (grant: ResolvedGrant) => Promise<Actor | null> | Actor | null;
25
+ /** `oauth.resourceName`: what a client's consent screen shows. */
26
+ readonly resourceName?: string | undefined;
27
+ /** Where the `mcp.auth.*` lines go. The process logger unless a test reads them. */
28
+ readonly log?: Logger | undefined;
29
+ }
30
+
31
+ export interface McpAuthorizationServer extends AuthorizationServer {
32
+ readonly resource: string;
33
+ /** Hand to `defineAppMcp({ oauth })`: the 401 then names this server. */
34
+ readonly oauth: McpOAuth;
35
+ /** Hand to `defineAppMcp({ resolveToken })`: a token bound to `resource`, or `null`. */
36
+ resolveToken(token: string): Promise<ResolvedToken | null>;
37
+ }
38
+
39
+ /** Replays are the shape of a stolen credential: `warn`, the level an alert rule reads. */
40
+ const WARN_KINDS: ReadonlySet<AuthServerEvent['kind']> = new Set([
41
+ 'code-replayed',
42
+ 'refresh-replayed',
43
+ 'grant-disabled',
44
+ ]);
45
+
46
+ export function mcpAuthorizationServer(
47
+ options: McpAuthorizationServerOptions,
48
+ ): McpAuthorizationServer {
49
+ const log = options.log ?? logger;
50
+ const resources = [options.resource, ...(options.resources ?? [])];
51
+ const server = authorizationServer({
52
+ ...options,
53
+ resources: [...new Set(resources)],
54
+ // A client that names no resource still gets a token for THIS endpoint, never an unbound one.
55
+ defaultResource: options.resource,
56
+ onEvent(event) {
57
+ const fields = {
58
+ surface: 'mcp',
59
+ ...(event.error === undefined ? {} : { error: event.error }),
60
+ ...(event.grantType === undefined ? {} : { grantType: event.grantType }),
61
+ ...(event.clientId === undefined ? {} : { clientId: event.clientId }),
62
+ };
63
+ if (WARN_KINDS.has(event.kind)) log.warn(`mcp.auth.${event.kind}`, fields);
64
+ else log.info(`mcp.auth.${event.kind}`, fields);
65
+ options.onEvent?.(event);
66
+ },
67
+ });
68
+ const resolve = oauthBearerResolver(server, { actor: options.actor, resource: options.resource });
69
+ return {
70
+ ...server,
71
+ resource: options.resource,
72
+ oauth: {
73
+ authorizationServers: [server.issuer],
74
+ resource: options.resource,
75
+ scopesSupported: options.scopes,
76
+ ...(options.resourceName === undefined ? {} : { resourceName: options.resourceName }),
77
+ },
78
+ resolveToken: resolve,
79
+ };
80
+ }
@@ -4,18 +4,18 @@
4
4
  // primitive out is a different way to NAME a tool, never a second way to run one.
5
5
 
6
6
  import type { AnyAction } from '@ultimat3/action';
7
- import { actionName, guardActionBeforeInput, invoke, isAction } from '@ultimat3/action';
7
+ import { actionName, admitActionCaller, asCallerContext, invoke, isAction } from '@ultimat3/action';
8
8
  import {
9
9
  type Actor,
10
10
  actorOf,
11
11
  isMcpExposed,
12
12
  type McpExposureDeclaration,
13
+ toolDescription,
13
14
  useContext,
14
15
  } from '@ultimat3/core';
15
16
  import type { AnyQuery } from '@ultimat3/query';
16
17
  import { guardQueryBeforeInput, isQuery, queryName, readAnswer, sourceFor } from '@ultimat3/query';
17
18
  import { toWireOutputSchema, toWireSchema } from '@ultimat3/schema';
18
- import { asCallerContext } from './caller-context';
19
19
  import type { ProjectablePrimitive } from './from-action';
20
20
  import { takeIdempotencyKeyArg, withIdempotencyKeyArg } from './idempotency-arg';
21
21
  import type { JsonSchema } from './wire';
@@ -46,10 +46,10 @@ export function asProjectable(listed: ListedPrimitive): ProjectablePrimitive {
46
46
  }
47
47
 
48
48
  export function primitiveFromAction(target: AnyAction): ProjectablePrimitive {
49
- const exposure = exposureOf(target.mcp);
50
49
  // Throws `X_ACTION_UNREGISTERED` on an unnamed action rather than projecting a tool called
51
50
  // `''`: a nameless tool is unaddressable by the scope map, by `tools/call`, and by the author.
52
51
  const name = actionName(target);
52
+ const exposure = exposureOf(target.mcp, name, target.errors, true);
53
53
  const wire = toWireSchema(target.input);
54
54
  // `idempotent: true` is honoured on this surface exactly as over HTTP: the caller's key reaches
55
55
  // `invoke`, which files it under the action, the caller and the key (`idempotencyKeyFor`).
@@ -64,11 +64,7 @@ export function primitiveFromAction(target: AnyAction): ProjectablePrimitive {
64
64
  mutates: true,
65
65
  idempotent: keyed,
66
66
  // The same gate `invoke` opens with, asked by the server before it answers `invalid-args`.
67
- admit: (actor: Actor) =>
68
- asCallerContext(actor, () => {
69
- const ctx = useContext();
70
- guardActionBeforeInput(target.policy, { actor: actorOf(ctx), ctx, action: name }, 'mcp');
71
- }),
67
+ admit: admitActionCaller(target, name),
72
68
  // The actor rides in on the options: `invoke` swaps it inside the one execution path.
73
69
  run: keyed
74
70
  ? ({ input: args, actor }) => {
@@ -80,7 +76,6 @@ export function primitiveFromAction(target: AnyAction): ProjectablePrimitive {
80
76
  }
81
77
 
82
78
  export function primitiveFromQuery(target: AnyQuery): ProjectablePrimitive {
83
- const exposure = exposureOf(target.mcp);
84
79
  // A `single: true` read answers ONE row, or not-found — what its route answers (404) and what
85
80
  // `@ultimat3/query`'s `readAnswer` makes every read answer. Handing an agent `[]` for a missing id said "found, and empty".
86
81
  const single = target.single === true;
@@ -89,6 +84,7 @@ export function primitiveFromQuery(target: AnyQuery): ProjectablePrimitive {
89
84
  // is an object by the spec; a single read's answer already IS the object.
90
85
  const output = single ? toWireOutputSchema(target.rows) : toRowsOutputSchema(target.rows);
91
86
  const name = queryName(target);
87
+ const exposure = exposureOf(target.mcp, name, target.errors, false);
92
88
  return {
93
89
  name,
94
90
  ...(exposure === undefined ? {} : { mcp: exposure }),
@@ -144,11 +140,20 @@ export function toRowsOutputSchema(rows: unknown): JsonSchema | undefined {
144
140
  */
145
141
  function exposureOf(
146
142
  declared: McpExposureDeclaration | undefined,
143
+ name: string,
144
+ errors: readonly string[] | undefined,
145
+ mutates: boolean,
147
146
  ): McpExposureDeclaration | undefined {
148
147
  if (declared === undefined) return undefined;
148
+ // A declared `errors:` ends the description (core's `toolDescription`, `@ultimat3/ai`'s too), so
149
+ // a tool with none written gets the default lead spelled out before the list.
150
+ const description =
151
+ errors === undefined || errors.length === 0
152
+ ? declared.description
153
+ : toolDescription({ name, mcp: declared, mutates }, errors);
149
154
  return {
150
155
  expose: isMcpExposed(declared),
151
- ...(declared.description === undefined ? {} : { description: declared.description }),
156
+ ...(description === undefined ? {} : { description }),
152
157
  ...(declared.visibleTo === undefined ? {} : { visibleTo: declared.visibleTo }),
153
158
  ...(declared.listParams === undefined ? {} : { listParams: declared.listParams }),
154
159
  ...(declared.effect === undefined ? {} : { effect: declared.effect }),