@arbol-ai/maximus 0.0.0-stage → 7.0.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 (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +51 -2
  3. package/config/oxfmt.d.mts +8 -0
  4. package/config/oxfmt.mjs +30 -0
  5. package/config/oxlint-plugin.mjs +41 -0
  6. package/config/oxlint.d.mts +8 -0
  7. package/config/oxlint.mjs +118 -0
  8. package/dist/analytics/analytics.d.ts +34 -0
  9. package/dist/analytics/analytics.js +62 -0
  10. package/dist/body.d.ts +2 -0
  11. package/dist/body.js +4 -0
  12. package/dist/chunks/body-BcMbreNd.js +106 -0
  13. package/dist/chunks/correlation-gaiEoMBr.js +45 -0
  14. package/dist/chunks/execution-qfZuMSIu.js +700 -0
  15. package/dist/chunks/json-Dwni3u4c.js +63 -0
  16. package/dist/chunks/record-D2H3cg8S.js +36 -0
  17. package/dist/chunks/schemas-q-51wBMQ.js +216 -0
  18. package/dist/chunks/src-Ph5KHCRP.js +1160 -0
  19. package/dist/chunks/telemetry-DvZgrzZn.js +220 -0
  20. package/dist/chunks/types-CGwAhnTE.d.ts +1630 -0
  21. package/dist/chunks/validation-DWxKk1Js.js +382 -0
  22. package/dist/client/client.d.ts +131 -0
  23. package/dist/client/client.js +325 -0
  24. package/dist/diagnostics.d.ts +41 -0
  25. package/dist/diagnostics.js +4 -0
  26. package/dist/errors.d.ts +2 -0
  27. package/dist/errors.js +128 -0
  28. package/dist/http-paths.d.ts +2 -0
  29. package/dist/http-paths.js +200 -0
  30. package/dist/index.d.ts +2 -0
  31. package/dist/index.js +11 -0
  32. package/dist/internals.d.ts +2 -0
  33. package/dist/internals.js +5 -0
  34. package/dist/mcp/index.d.ts +12 -0
  35. package/dist/mcp/index.js +406 -0
  36. package/dist/postgres/index.d.ts +81 -0
  37. package/dist/postgres/index.js +140 -0
  38. package/dist/schemas.d.ts +2 -0
  39. package/dist/schemas.js +4 -0
  40. package/dist/standard-failures.d.ts +91 -0
  41. package/dist/standard-failures.js +75 -0
  42. package/dist/tooling/cli.js +110 -0
  43. package/dist/tooling/testing.d.ts +7 -0
  44. package/dist/tooling/testing.js +21 -0
  45. package/dist/webhooks.d.ts +69 -0
  46. package/dist/webhooks.js +162 -0
  47. package/dist/workers/runtime.d.ts +112 -0
  48. package/dist/workers/runtime.js +228 -0
  49. package/package.json +153 -4
  50. package/skills/maximus/SKILL.md +89 -0
  51. package/skills/maximus/references/adding-an-operation.md +179 -0
  52. package/skills/maximus/references/building-a-service.md +158 -0
  53. package/skills/maximus/references/errors-and-results.md +77 -0
  54. package/skills/maximus/references/migration-from-v2.md +62 -0
  55. package/skills/maximus/references/migration-to-v5.md +37 -0
  56. package/skills/maximus/references/publishing-and-verification.md +39 -0
  57. package/skills/maximus/references/testing.md +73 -0
  58. package/skills/maximus/references/transports.md +119 -0
  59. package/templates/service/.agents/skills/project/SKILL.md.template +10 -0
  60. package/templates/service/.github/workflows/ci.yml.template +21 -0
  61. package/templates/service/.gitignore.template +8 -0
  62. package/templates/service/CLAUDE.md.template +3 -0
  63. package/templates/service/README.md.template +45 -0
  64. package/templates/service/cloudflare.config.ts.template +30 -0
  65. package/templates/service/oxfmt.config.ts.template +1 -0
  66. package/templates/service/oxlint.config.ts.template +1 -0
  67. package/templates/service/package.json.template +31 -0
  68. package/templates/service/src/app.ts.template +30 -0
  69. package/templates/service/src/index.ts.template +13 -0
  70. package/templates/service/tests/contract.test.ts.template +12 -0
  71. package/templates/service/tsconfig.json.template +16 -0
  72. package/templates/service/vite.config.ts.template +7 -0
  73. package/templates/service/vitest.config.ts.template +10 -0
@@ -0,0 +1,200 @@
1
+ //#region src/http-paths.ts
2
+ /**
3
+ * `@arbol-ai/maximus/http-paths`: versioned route templates, path parameter decoding, and the router that
4
+ * matches a request to exactly one operation.
5
+ */
6
+ /** A fixed path segment of a route template. */
7
+ const STATIC_SEGMENT = /^[a-zA-Z0-9_-]+$/;
8
+ /** A parameter segment of a route template, `{name}`, occupying the whole segment. */
9
+ const PARAMETER_SEGMENT = /^\{([a-zA-Z][a-zA-Z0-9_]*)\}$/;
10
+ /** Parameter names that would reach an object's prototype. */
11
+ const UNSAFE_PARAMETERS = /* @__PURE__ */ new Set([
12
+ "constructor",
13
+ "prototype",
14
+ "__proto__"
15
+ ]);
16
+ /** Headers that carry authority or framing: never an operation's input metadata. */
17
+ const RESERVED_HEADERS = /* @__PURE__ */ new Set([
18
+ "authorization",
19
+ "cookie",
20
+ "host",
21
+ "content-length",
22
+ "content-encoding"
23
+ ]);
24
+ /** Whether a byte operation may read one of its input fields from this header. */
25
+ function isInputHeaderName(header) {
26
+ return /^[A-Za-z0-9-]+$/u.test(header) && !RESERVED_HEADERS.has(header.toLowerCase());
27
+ }
28
+ /** Parse declared templates, never caller paths. Parameters occupy one complete path segment. */
29
+ function operationPathParameters(path) {
30
+ const segments = path.split("/");
31
+ if (segments[0] !== "" || !/^v[1-9][0-9]*$/.test(segments[1] ?? "") || segments.length < 3) throw new TypeError("Operations require a versioned path.");
32
+ const parameters = [];
33
+ for (const segment of segments.slice(2)) {
34
+ const parameter = PARAMETER_SEGMENT.exec(segment)?.[1];
35
+ if (parameter) {
36
+ if (UNSAFE_PARAMETERS.has(parameter) || parameters.includes(parameter)) throw new TypeError("Path parameter names must be unique and safe.");
37
+ parameters.push(parameter);
38
+ } else if (!STATIC_SEGMENT.test(segment)) throw new TypeError("Use fixed routes or complete {parameter} segments; empty and malformed segments are forbidden.");
39
+ }
40
+ return parameters;
41
+ }
42
+ /** A decoded item key stays in one segment; dot segments and controls cannot alter URL ownership. */
43
+ function decodePathParameter(segment) {
44
+ try {
45
+ const value = decodeURIComponent(segment);
46
+ return isPathParameterValue(value) ? value : null;
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+ /** Item keys are nonempty strings that cannot change URL path ownership when encoded. */
52
+ function isPathParameterValue(value) {
53
+ if (typeof value !== "string" || value.length === 0 || value === "." || value === ".." || /[\\/]/.test(value)) return false;
54
+ for (const character of value) {
55
+ const code = character.charCodeAt(0);
56
+ if (code < 32 || code === 127) return false;
57
+ }
58
+ return true;
59
+ }
60
+ /** The methods an operation route may use. */
61
+ const HTTP_METHODS = /* @__PURE__ */ new Set([
62
+ "GET",
63
+ "POST",
64
+ "PUT",
65
+ "PATCH",
66
+ "DELETE"
67
+ ]);
68
+ /**
69
+ * Exact routes use a Map. Template branches compile into deterministic states at construction:
70
+ * one transition per segment, including overlapping fixed prefixes, with no per-request route scan.
71
+ */
72
+ function createHttpRouteResolver(definitions) {
73
+ const exact = /* @__PURE__ */ new Map();
74
+ const roots = /* @__PURE__ */ new Map();
75
+ let nextId = 0;
76
+ /** A new tree node with the next id. */
77
+ const branch = () => {
78
+ const node = {
79
+ id: nextId,
80
+ fixed: /* @__PURE__ */ new Map()
81
+ };
82
+ nextId += 1;
83
+ return node;
84
+ };
85
+ for (const definition of definitions) {
86
+ if (!definition.http) continue;
87
+ if (!HTTP_METHODS.has(definition.http.method)) throw new TypeError("Operation routes require a supported HTTP method.");
88
+ const names = operationPathParameters(definition.http.path);
89
+ const segments = definition.http.path.slice(1).split("/");
90
+ const route = {
91
+ definition,
92
+ parameters: segments.flatMap((segment, position) => {
93
+ const parameter = segment.startsWith("{") ? segment.slice(1, -1) : void 0;
94
+ return parameter ? [{
95
+ name: parameter,
96
+ position
97
+ }] : [];
98
+ })
99
+ };
100
+ if (names.length === 0) {
101
+ const key = `${definition.http.method} ${definition.http.path}`;
102
+ if (exact.has(key)) throw new TypeError("Duplicate operation route.");
103
+ exact.set(key, route);
104
+ continue;
105
+ }
106
+ let node = roots.get(definition.http.method);
107
+ if (!node) {
108
+ node = branch();
109
+ roots.set(definition.http.method, node);
110
+ }
111
+ for (const segment of segments) if (segment.startsWith("{")) {
112
+ node.parameter ??= branch();
113
+ node = node.parameter;
114
+ } else {
115
+ let child = node.fixed.get(segment);
116
+ if (!child) {
117
+ child = branch();
118
+ node.fixed.set(segment, child);
119
+ }
120
+ node = child;
121
+ }
122
+ if (node.route) throw new TypeError("Ambiguous operation path templates.");
123
+ node.route = route;
124
+ }
125
+ const states = /* @__PURE__ */ new Map();
126
+ /**
127
+ * The state for a set of tree nodes: their routes (at most one), and for each next segment the state of
128
+ * every node it can lead to, compiled once per set.
129
+ */
130
+ function compile(nodes) {
131
+ const distinct = [...new Map(nodes.map((node) => [node.id, node])).values()];
132
+ const key = distinct.map((node) => node.id).toSorted((left, right) => left - right).join(",");
133
+ const known = states.get(key);
134
+ if (known) return known;
135
+ const routes = distinct.flatMap((node) => node.route ? [node.route] : []);
136
+ if (routes.length > 1) throw new TypeError("Ambiguous overlapping operation path templates.");
137
+ const state = {
138
+ fixed: /* @__PURE__ */ new Map(),
139
+ route: routes[0]
140
+ };
141
+ states.set(key, state);
142
+ const parameters = distinct.flatMap((node) => node.parameter ? [node.parameter] : []);
143
+ if (parameters.length > 0) state.parameter = compile(parameters);
144
+ const fixed = new Set(distinct.flatMap((node) => [...node.fixed.keys()]));
145
+ for (const segment of fixed) {
146
+ const children = distinct.flatMap((node) => {
147
+ const child = node.fixed.get(segment);
148
+ return child ? [child] : [];
149
+ });
150
+ state.fixed.set(segment, compile([...children, ...parameters]));
151
+ }
152
+ return state;
153
+ }
154
+ const templates = new Map([...roots].map(([method, root]) => [method, compile([root])]));
155
+ /**
156
+ * The route for a method and path: an exact route first, then one transition per segment through the
157
+ * compiled states.
158
+ */
159
+ function findRoute(method, path) {
160
+ const fixed = exact.get(`${method} ${path}`);
161
+ if (fixed) return fixed;
162
+ if (!path.startsWith("/") || path.endsWith("/")) return null;
163
+ const segments = path.slice(1).split("/");
164
+ let state = templates.get(method);
165
+ for (const segment of segments) {
166
+ if (!segment || !state) return null;
167
+ state = state.fixed.get(segment) ?? state.parameter;
168
+ }
169
+ return state?.route ?? null;
170
+ }
171
+ /**
172
+ * The route a request reaches, with its path parameters decoded; null when none matches or a parameter
173
+ * value is unsafe.
174
+ */
175
+ function match(method, path) {
176
+ const route = findRoute(method, path);
177
+ if (!route) return null;
178
+ const segments = path.slice(1).split("/");
179
+ const parameters = {};
180
+ for (const parameter of route.parameters) {
181
+ const value = decodePathParameter(segments[parameter.position] ?? "");
182
+ if (value === null) return null;
183
+ parameters[parameter.name] = value;
184
+ }
185
+ return {
186
+ definition: route.definition,
187
+ parameters
188
+ };
189
+ }
190
+ return {
191
+ match,
192
+ /** Used only at construction to prevent a transport from bypassing item-route authorization. */
193
+ ownsPath(path) {
194
+ return [...HTTP_METHODS].some((method) => findRoute(method, path) !== null);
195
+ }
196
+ };
197
+ }
198
+
199
+ //#endregion
200
+ export { createHttpRouteResolver, decodePathParameter, isInputHeaderName, isPathParameterValue, operationPathParameters };
@@ -0,0 +1,2 @@
1
+ import { $ as PageQuery, A as EmptyInputSchema, An as FailureData, At as AppManifest, B as EmailAddressSchema, Cn as isResult, D as RouteContext, Dn as ErrorDefinition, Dt as ApplicationBuilder, E as HttpTransport, En as ErrorCatalog, Et as parseSchema, Ft as McpGuide, G as PhoneNumberSchema, Gt as AdmissionObservation, H as HttpsUrlSchema, Hn as AttachmentOutputSchema, I as UuidSchema, It as McpSkill, J as SignedUrl, Jt as Observer, K as PostalAddress, Kt as BackgroundContext, Lt as OperationMiddleware, Mn as defineErrors, Mt as Invocation, Nn as resultSchema, Nt as InvocationAuthority, O as TransportContext, On as ErrorFactory, Ot as ApplicationConfiguration, Pn as standardErrors, Pt as McpConfiguration, Q as PageInfoSchema, Qt as reportUnexpected, R as DeletedObject, Rt as OperationScope, Sn as err, T as HttpRoute, Tn as DefinedErrors, Tt as parseInput, U as NamedReference, Ut as operationMatchesScopes, V as HexColorSchema, Vn as Attachment, Vt as isPublicOperation, W as NamedReferenceSchema, Wt as operationScopes, X as Page, Y as SignedUrlSchema, Yt as TelemetryConfig, Z as PageInfo, _ as HttpRouteDefinition, _n as matchesScopes, a as Type, an as TokenClient, bn as Result, c as isJsonMediaType, cn as TokenPrincipal, d as retryAfterSeconds, dn as createTokenAuthorization, et as PageQueryFields, f as BodyReadOptions, fn as createTokenVerifier, g as readBodyText, gn as ScopeMatch, h as readBodyBytes, hn as protectedResourceMetadata, i as TSchema, in as TokenClaims, j as OrganizationIdSchema, jn as FailureSchema, jt as Exposure, k as createHttpHandler, kn as Failure, kt as maximus, l as readJsonBody, ln as TokenResolutionContext, m as HttpBodyFailureReason, mn as OAuthResource, nn as PrincipalSchema, nt as pageLimit, o as t, on as TokenDevelopment, p as HttpBodyFailure, pn as projectToken, q as PostalAddressSchema, qt as ExecutionObservation, r as Static, rn as TokenAlgorithm, s as createOpenApi, sn as TokenPolicy, tn as Principal, tt as TPage, u as readJsonResponse, un as TokenScheme, v as HttpRouteMatch, vn as BinaryBody, w as HttpOptions, wn as ok, xn as Success, y as createHttpRouteResolver, yn as FailureResult, z as DeletedObjectSchema, zt as OperationShape } from "./chunks/types-CGwAhnTE.js";
2
+ export { type AdmissionObservation, type AppManifest, type ApplicationBuilder, type ApplicationConfiguration, type Attachment, AttachmentOutputSchema, type BackgroundContext, type BinaryBody, type BodyReadOptions, type DefinedErrors, type DeletedObject, DeletedObjectSchema, EmailAddressSchema, EmptyInputSchema, type ErrorCatalog, type ErrorDefinition, type ErrorFactory, type ExecutionObservation, type Exposure, type Failure, type FailureData, type FailureResult, FailureSchema, HexColorSchema, type HttpBodyFailure, type HttpBodyFailureReason, type HttpOptions, type HttpRoute, type HttpRouteDefinition, type HttpRouteMatch, type HttpTransport, HttpsUrlSchema, type Invocation, type InvocationAuthority, type McpConfiguration, type McpGuide, type McpSkill, type NamedReference, NamedReferenceSchema, type OAuthResource, type Observer, type OperationMiddleware, type OperationScope, type OperationShape, OrganizationIdSchema, Page, type PageInfo, PageInfoSchema, type PageQuery, PageQueryFields, PhoneNumberSchema, type PostalAddress, PostalAddressSchema, type Principal, PrincipalSchema, type Result, type RouteContext, type ScopeMatch, type SignedUrl, SignedUrlSchema, type Static, type Success, type TPage, type TSchema, type TelemetryConfig, type TokenAlgorithm, type TokenClaims, type TokenClient, type TokenDevelopment, type TokenPolicy, type TokenPrincipal, type TokenResolutionContext, type TokenScheme, type TransportContext, Type, UuidSchema, createHttpHandler, createHttpRouteResolver, createOpenApi, createTokenAuthorization, createTokenVerifier, defineErrors, err, isJsonMediaType, isPublicOperation, isResult, matchesScopes, maximus, ok, operationMatchesScopes, operationScopes, pageLimit, parseInput, parseSchema, projectToken, protectedResourceMetadata, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, reportUnexpected, resultSchema, retryAfterSeconds, standardErrors, t };
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ import { i as parseSchema, r as parseInput } from "./chunks/validation-DWxKk1Js.js";
2
+ import { FailureSchema, defineErrors, resultSchema, standardErrors } from "./errors.js";
3
+ import { n as readBodyBytes, r as readBodyText } from "./chunks/body-BcMbreNd.js";
4
+ import { C as operationMatchesScopes, E as matchesScopes, T as operationScopes, a as createTokenVerifier, d as err, f as isResult, i as createTokenAuthorization, o as projectToken, p as ok, r as PrincipalSchema, y as isPublicOperation } from "./chunks/execution-qfZuMSIu.js";
5
+ import { createHttpRouteResolver } from "./http-paths.js";
6
+ import { _ as pageLimit, c as HexColorSchema, d as PhoneNumberSchema, f as PostalAddressSchema, g as PageQueryFields, h as PageInfoSchema, i as UuidSchema, l as HttpsUrlSchema, m as Page, n as OrganizationIdSchema, o as DeletedObjectSchema, p as SignedUrlSchema, s as EmailAddressSchema, t as EmptyInputSchema, u as NamedReferenceSchema, v as AttachmentOutputSchema } from "./chunks/schemas-q-51wBMQ.js";
7
+ import { c as maximus, i as createOpenApi, n as t, r as createHttpHandler, s as protectedResourceMetadata, t as Type } from "./chunks/src-Ph5KHCRP.js";
8
+ import { i as reportUnexpected } from "./chunks/telemetry-DvZgrzZn.js";
9
+ import { a as retryAfterSeconds, i as readJsonResponse, r as readJsonBody, t as isJsonMediaType } from "./chunks/json-Dwni3u4c.js";
10
+
11
+ export { AttachmentOutputSchema, DeletedObjectSchema, EmailAddressSchema, EmptyInputSchema, FailureSchema, HexColorSchema, HttpsUrlSchema, NamedReferenceSchema, OrganizationIdSchema, Page, PageInfoSchema, PageQueryFields, PhoneNumberSchema, PostalAddressSchema, PrincipalSchema, SignedUrlSchema, Type, UuidSchema, createHttpHandler, createHttpRouteResolver, createOpenApi, createTokenAuthorization, createTokenVerifier, defineErrors, err, isJsonMediaType, isPublicOperation, isResult, matchesScopes, maximus, ok, operationMatchesScopes, operationScopes, pageLimit, parseInput, parseSchema, projectToken, protectedResourceMetadata, readBodyBytes, readBodyText, readJsonBody, readJsonResponse, reportUnexpected, resultSchema, retryAfterSeconds, standardErrors, t };
@@ -0,0 +1,2 @@
1
+ import { $t as telemetryEnabled, At as AppManifest, Bt as composeOperations, E as HttpTransport, Ht as operation, Kt as BackgroundContext, Lt as OperationMiddleware, Mt as Invocation, Nt as InvocationAuthority, O as TransportContext, Wt as operationScopes, Yt as TelemetryConfig, Zt as recordExecution, _ as HttpRouteDefinition, en as withDiagnostics, n as executeOperation, t as defineApp, v as HttpRouteMatch, w as HttpOptions, y as createHttpRouteResolver, zt as OperationShape } from "./chunks/types-CGwAhnTE.js";
2
+ export { type AppManifest, type BackgroundContext, type HttpOptions, type HttpRouteDefinition, type HttpRouteMatch, type HttpTransport, type Invocation, type InvocationAuthority, type OperationMiddleware, type OperationShape, type TelemetryConfig, type TransportContext, composeOperations, createHttpRouteResolver, defineApp, executeOperation, operation, operationScopes, recordExecution, telemetryEnabled, withDiagnostics };
@@ -0,0 +1,5 @@
1
+ import { T as operationScopes, n as defineApp, t as executeOperation, v as composeOperations, x as operation } from "./chunks/execution-qfZuMSIu.js";
2
+ import { createHttpRouteResolver } from "./http-paths.js";
3
+ import { a as telemetryEnabled, o as withDiagnostics, r as recordExecution } from "./chunks/telemetry-DvZgrzZn.js";
4
+
5
+ export { composeOperations, createHttpRouteResolver, defineApp, executeOperation, operation, operationScopes, recordExecution, telemetryEnabled, withDiagnostics };
@@ -0,0 +1,12 @@
1
+ import { E as HttpTransport } from "../chunks/types-CGwAhnTE.js";
2
+ //#region src/mcp/index.d.ts
3
+ /**
4
+ * The MCP transport, for `createWorker(app, { transports: [mcp()] })`: serves the operations that declare
5
+ * `mcp` as tools over Streamable HTTP at `/mcp` (or `path`), with the OpenAPI document and guides as
6
+ * resources, guides as prompts and skills through the Skills extension. A caller needs `<namespace>:mcp:use`
7
+ * and sees only the tools its scopes admit.
8
+ */
9
+ export declare function mcp(options?: {
10
+ path?: string;
11
+ }): HttpTransport;
12
+ //#endregion
@@ -0,0 +1,406 @@
1
+ import { standardErrors } from "../errors.js";
2
+ import { C as operationMatchesScopes, b as mcpOpenWorld, g as MAX_BODY_BYTES_CEILING, m as sha256Hex } from "../chunks/execution-qfZuMSIu.js";
3
+ import { a as canonical, o as standaloneSchema } from "../chunks/src-Ph5KHCRP.js";
4
+ import { i as reportUnexpected } from "../chunks/telemetry-DvZgrzZn.js";
5
+ import { Type } from "@sinclair/typebox";
6
+ import { Value } from "@sinclair/typebox/value";
7
+ import { stringify } from "yaml";
8
+ import { McpServer, ProtocolError, ProtocolErrorCode, createMcpHandler } from "@modelcontextprotocol/server";
9
+
10
+ //#region src/mcp/skills.ts
11
+ /**
12
+ * The MCP Skills extension (SEP-2640): `skills/list` and `skills/get` describe each skill by its
13
+ * frontmatter and the manifest of its one file, whose size and SHA-256 digest hosts verify, and
14
+ * `resources/read` serves that `SKILL.md`. An optional tool serves the same skills to clients that import
15
+ * only tools.
16
+ */
17
+ /** The official Skills extension (SEP-2640) a server declares in its capabilities. */
18
+ const SKILLS_EXTENSION = "io.modelcontextprotocol/skills";
19
+ /** Skills change only with a deployment and are the same for every caller, so hosts may share them. */
20
+ const SKILL_CACHE = {
21
+ ttlMs: 3e5,
22
+ cacheScope: "public"
23
+ };
24
+ /** Adapts a TypeBox schema to the Standard Schema the SDK validates custom method params with. */
25
+ function standardSchema(schema) {
26
+ return { "~standard": {
27
+ version: 1,
28
+ vendor: "maximus",
29
+ validate: (value) => Value.Check(schema, value) ? { value } : { issues: [{ message: "Invalid params" }] }
30
+ } };
31
+ }
32
+ /** `skills/list` params: an optional page cursor, which one page of every skill never issues. */
33
+ const ListSkillsParams = standardSchema(Type.Object({ cursor: Type.Optional(Type.String()) }));
34
+ /** `skills/get` params: the URI of the skill's `SKILL.md`. */
35
+ const GetSkillParams = standardSchema(Type.Object({ uri: Type.String() }));
36
+ /**
37
+ * A skill's `SKILL.md` URI, `skill://<name>/SKILL.md`: the file's directory carries the skill's name, as
38
+ * SEP-2640 requires.
39
+ */
40
+ function skillUri(skill) {
41
+ return `skill://${skill.name}/SKILL.md`;
42
+ }
43
+ /** The served `SKILL.md`: frontmatter generated from the name and description, then the instructions. */
44
+ function skillDocument(skill) {
45
+ return `---\n${stringify({
46
+ name: skill.name,
47
+ description: skill.description
48
+ }, { lineWidth: 0 })}---\n\n${skill.text.trim()}\n`;
49
+ }
50
+ /** A catalog entry. Hosts verify every file they read against its manifest's size and SHA-256 digest. */
51
+ async function skillEntry(skill) {
52
+ const uri = skillUri(skill);
53
+ const bytes = new TextEncoder().encode(skillDocument(skill));
54
+ return {
55
+ uri,
56
+ frontmatter: {
57
+ name: skill.name,
58
+ description: skill.description
59
+ },
60
+ resources: [{
61
+ uri,
62
+ digest: `sha256:${await sha256Hex(bytes)}`,
63
+ size: bytes.byteLength
64
+ }]
65
+ };
66
+ }
67
+ /**
68
+ * Serve skills through the Skills extension: `skills/list`, `skills/get`, and `resources/read` of each
69
+ * `SKILL.md`, each request answered through `answer`, which counts it against the caller's rate limit.
70
+ * Clients without the extension still find the files among the server's resources.
71
+ */
72
+ function registerSkills(server, skills, answer) {
73
+ for (const skill of skills) {
74
+ const uri = skillUri(skill);
75
+ server.registerResource(skill.name, uri, {
76
+ description: skill.description,
77
+ mimeType: "text/markdown",
78
+ cacheHint: SKILL_CACHE
79
+ }, () => answer(() => ({ contents: [{
80
+ uri,
81
+ mimeType: "text/markdown",
82
+ text: skillDocument(skill)
83
+ }] })));
84
+ }
85
+ server.server.setRequestHandler("skills/list", { params: ListSkillsParams }, (params) => answer(async () => {
86
+ if (params.cursor !== void 0) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Invalid skills cursor");
87
+ return {
88
+ resultType: "complete",
89
+ skills: await Promise.all(skills.map(skillEntry)),
90
+ ...SKILL_CACHE
91
+ };
92
+ }));
93
+ server.server.setRequestHandler("skills/get", { params: GetSkillParams }, (params) => answer(async () => {
94
+ const skill = skills.find((candidate) => skillUri(candidate) === params.uri);
95
+ if (!skill) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Unknown skill");
96
+ return {
97
+ resultType: "complete",
98
+ skill: await skillEntry(skill),
99
+ ...SKILL_CACHE
100
+ };
101
+ }));
102
+ }
103
+ /**
104
+ * The same skills as one read-only tool, for clients that import only tools. Its description names every
105
+ * skill, so a semantic tool search for one of those tasks can find it.
106
+ */
107
+ function skillTool(name, skills) {
108
+ return {
109
+ name,
110
+ title: "Read a workflow skill",
111
+ description: [
112
+ "Read the instructions of one workflow skill before doing its task: the steps, tools and pitfalls of work that spans several tools. A skill grants no tools or permissions.",
113
+ "Skills:",
114
+ ...skills.map((skill) => `- ${skill.name}: ${skill.description}`)
115
+ ].join("\n"),
116
+ inputSchema: {
117
+ type: "object",
118
+ properties: { name: {
119
+ type: "string",
120
+ enum: skills.map((skill) => skill.name),
121
+ description: "The skill to read."
122
+ } },
123
+ required: ["name"],
124
+ additionalProperties: false
125
+ },
126
+ outputSchema: {
127
+ type: "object",
128
+ properties: {
129
+ name: { type: "string" },
130
+ description: { type: "string" },
131
+ instructions: {
132
+ type: "string",
133
+ description: "The Markdown instructions."
134
+ }
135
+ },
136
+ required: [
137
+ "name",
138
+ "description",
139
+ "instructions"
140
+ ],
141
+ additionalProperties: false
142
+ },
143
+ annotations: {
144
+ readOnlyHint: true,
145
+ destructiveHint: false,
146
+ idempotentHint: true,
147
+ openWorldHint: false
148
+ }
149
+ };
150
+ }
151
+ /** Answer a skill tool call. An unknown name is a tool error, which the model can correct. */
152
+ function readSkill(skills, input) {
153
+ const skill = skills.find((candidate) => candidate.name === input.name);
154
+ if (!skill) return {
155
+ isError: true,
156
+ content: [{
157
+ type: "text",
158
+ text: `Unknown skill. Read one of: ${skills.map((entry) => entry.name).join(", ")}.`
159
+ }]
160
+ };
161
+ const value = {
162
+ name: skill.name,
163
+ description: skill.description,
164
+ instructions: skill.text.trim()
165
+ };
166
+ return {
167
+ content: [{
168
+ type: "text",
169
+ text: JSON.stringify(value)
170
+ }],
171
+ structuredContent: value
172
+ };
173
+ }
174
+
175
+ //#endregion
176
+ //#region src/mcp/index.ts
177
+ /**
178
+ * `@arbol-ai/maximus/mcp`: the MCP transport. One stateless server per request, built with the official SDK,
179
+ * lists the caller's tools and runs them through the shared execution path, and serves the OpenAPI document
180
+ * and the guides as resources, the guides as prompts and the skills through the Skills extension.
181
+ */
182
+ /** Operation tools on one `tools/list` page; the skill tool, when served, comes before them on the first. */
183
+ const PAGE_SIZE = 50;
184
+ /** The JSON-RPC error of a request beyond the caller's rate limit: an implementation-defined server error. */
185
+ const RATE_LIMITED = -32e3;
186
+ /** Each operation's tool definition, built on first listing: an application's operations never change. */
187
+ const definitions = /* @__PURE__ */ new WeakMap();
188
+ /**
189
+ * The tool an operation lists as. Both schemas are self-contained, as MCP clients compile them: no `$id`,
190
+ * which one schema may not repeat. The hints follow the operation's effect and tool declaration; they are not
191
+ * authorization.
192
+ */
193
+ function toolDefinition(op) {
194
+ let tool = definitions.get(op);
195
+ if (!tool) {
196
+ tool = {
197
+ name: op.mcp.name,
198
+ title: op.title,
199
+ description: op.description,
200
+ inputSchema: toolInputSchema(op.input),
201
+ outputSchema: {
202
+ ...standaloneSchema(op.output),
203
+ type: "object"
204
+ },
205
+ annotations: {
206
+ readOnlyHint: op.effect === "read",
207
+ destructiveHint: op.effect === "delete",
208
+ idempotentHint: op.mcp.idempotent,
209
+ openWorldHint: mcpOpenWorld(op.mcp)
210
+ }
211
+ };
212
+ definitions.set(op, tool);
213
+ }
214
+ return tool;
215
+ }
216
+ /**
217
+ * An operation's input as a tool's `inputSchema`: an object at the root, as MCP requires and hosts enforce.
218
+ * A union input (`{ channel: 'email', … } | { channel: 'sms', … }`) lists as one object with every member's
219
+ * fields, required when every member requires them, and a field the members declare differently as their
220
+ * choices. Hosts that refuse a root `anyOf`, the Anthropic API among them, would fail every tool of the
221
+ * request; each call is still checked against the exact union.
222
+ */
223
+ function toolInputSchema(input) {
224
+ const schema = standaloneSchema(input);
225
+ const { anyOf, ...root } = schema;
226
+ const bundled = root.$defs ?? {};
227
+ const members = Array.isArray(anyOf) ? anyOf.map((member) => localDefinition(member, bundled)) : [];
228
+ if (!members.length || members.some((member) => member.type !== "object")) return {
229
+ ...schema,
230
+ type: "object"
231
+ };
232
+ const fields = (member) => member.properties ?? {};
233
+ const names = [...new Set(members.flatMap((member) => Object.keys(fields(member))))];
234
+ const required = names.filter((name) => members.every((member) => Array.isArray(member.required) && member.required.includes(name)));
235
+ return {
236
+ type: "object",
237
+ ...root,
238
+ properties: Object.fromEntries(names.map((name) => [name, fieldChoices(members.flatMap((member) => name in fields(member) ? [fields(member)[name] ?? {}] : []))])),
239
+ ...required.length ? { required } : {},
240
+ ...members.every((member) => member.additionalProperties === false) ? { additionalProperties: false } : {},
241
+ type: "object"
242
+ };
243
+ }
244
+ /** A union member, or the definition under `$defs` its `$ref` names. */
245
+ function localDefinition(member, bundled) {
246
+ const reference = typeof member.$ref === "string" ? member.$ref : "";
247
+ return reference.startsWith("#/$defs/") ? bundled[reference.slice(8)] ?? member : member;
248
+ }
249
+ /**
250
+ * One field of a listed union: the one schema every member that declares it gives it, the members' literals
251
+ * as an `enum` (a discriminator), or else each distinct schema as a choice.
252
+ */
253
+ function fieldChoices(schemas) {
254
+ const distinct = [...new Map(schemas.map((schema) => [canonical(schema), schema])).values()];
255
+ const [first] = distinct;
256
+ if (distinct.length === 1 && first) return first;
257
+ const literal = (schema) => "const" in schema && Object.keys(schema).every((key) => key === "const" || key === "type");
258
+ if (first && distinct.every(literal) && distinct.every((schema) => schema.type === first.type)) return {
259
+ ...first.type === void 0 ? {} : { type: first.type },
260
+ enum: distinct.map((schema) => schema.const)
261
+ };
262
+ return { anyOf: distinct };
263
+ }
264
+ /**
265
+ * The MCP transport, for `createWorker(app, { transports: [mcp()] })`: serves the operations that declare
266
+ * `mcp` as tools over Streamable HTTP at `/mcp` (or `path`), with the OpenAPI document and guides as
267
+ * resources, guides as prompts and skills through the Skills extension. A caller needs `<namespace>:mcp:use`
268
+ * and sees only the tools its scopes admit.
269
+ */
270
+ function mcp(options = {}) {
271
+ return {
272
+ protocol: "mcp",
273
+ path: options.path ?? "/mcp",
274
+ scope: (namespace) => `${namespace}:mcp:use`,
275
+ maxBodyBytes: (operations, fallback) => Math.max(fallback, ...operations.flatMap(([, op]) => op.mcp ? [op.maxBodyBytes ?? fallback] : [])),
276
+ async handle({ request, requestId, authenticated, application, operations, contractText, url, invoke, admitRequest, bodyBytes, bodyLimit }) {
277
+ /** The cursor of the page after the one that ends with an operation, valid for this version only. */
278
+ const pageCursor = (name) => `${application.version}:${name}`;
279
+ /**
280
+ * Counts one more request of this HTTP request against the caller's rate limit, as a request of its own
281
+ * (a JSON-RPC batch carries several), and refuses it once the limit does.
282
+ */
283
+ const count = async () => {
284
+ if (!await admitRequest()) {
285
+ const failure = standardErrors.rateLimited.create();
286
+ throw new ProtocolError(RATE_LIMITED, failure.message, failure);
287
+ }
288
+ };
289
+ /**
290
+ * Runs one of the server's own handlers as a counted request, unless `invoke` counts it: a protocol
291
+ * error answers as thrown, and any other failure is reported by its safe description and answers a
292
+ * generic internal error, never its message.
293
+ */
294
+ const answer = async (work, counted = true) => {
295
+ try {
296
+ if (counted) await count();
297
+ return await work();
298
+ } catch (error) {
299
+ if (error instanceof ProtocolError) throw error;
300
+ reportUnexpected(error, "mcp", requestId);
301
+ throw new ProtocolError(ProtocolErrorCode.InternalError, "Internal error");
302
+ }
303
+ };
304
+ const response = await createMcpHandler(() => {
305
+ const skills = application.mcp?.skills ?? [];
306
+ const skillToolName = skills.length ? application.mcp?.skillTool : void 0;
307
+ const server = new McpServer({
308
+ name: application.name,
309
+ title: application.title,
310
+ version: application.version
311
+ }, {
312
+ instructions: application.mcp?.instructions,
313
+ capabilities: {
314
+ tools: { listChanged: false },
315
+ resources: { listChanged: false },
316
+ prompts: { listChanged: false },
317
+ ...skills.length ? { extensions: { [SKILLS_EXTENSION]: {} } } : {}
318
+ }
319
+ });
320
+ const visible = operations.filter((entry) => Boolean(entry[1].mcp) && operationMatchesScopes(entry[1], authenticated.scopes) && (!entry[1].actorKinds || entry[1].actorKinds.includes(authenticated.actorKind)));
321
+ server.server.setRequestHandler("tools/call", (call) => answer(async () => {
322
+ if (skillToolName && call.params.name === skillToolName) {
323
+ await count();
324
+ return readSkill(skills, call.params.arguments ?? {});
325
+ }
326
+ const selected = visible.find(([, op]) => op.mcp.name === call.params.name);
327
+ if (!selected) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Tool not found");
328
+ const [name, op] = selected;
329
+ if (bodyBytes > bodyLimit(op)) return {
330
+ isError: true,
331
+ content: [{
332
+ type: "text",
333
+ text: JSON.stringify(standardErrors.tooLarge.create())
334
+ }]
335
+ };
336
+ const result = await invoke(name, op, call.params.arguments ?? {});
337
+ return result.ok ? {
338
+ content: [{
339
+ type: "text",
340
+ text: JSON.stringify(result.value)
341
+ }],
342
+ structuredContent: result.value
343
+ } : {
344
+ isError: true,
345
+ content: [{
346
+ type: "text",
347
+ text: JSON.stringify(result.error)
348
+ }]
349
+ };
350
+ }, false));
351
+ server.server.setRequestHandler("tools/list", (listing) => answer(() => {
352
+ const cursor = listing.params?.cursor;
353
+ const previous = cursor === void 0 ? -1 : visible.findIndex(([name]) => pageCursor(name) === cursor);
354
+ if (cursor !== void 0 && previous < 0) throw new ProtocolError(ProtocolErrorCode.InvalidParams, "Invalid cursor");
355
+ const page = visible.slice(previous + 1, previous + 1 + PAGE_SIZE);
356
+ const last = page.at(-1);
357
+ return {
358
+ tools: [...skillToolName && cursor === void 0 ? [skillTool(skillToolName, skills)] : [], ...page.map(([, op]) => toolDefinition(op))],
359
+ ...last && previous + 1 + PAGE_SIZE < visible.length ? { nextCursor: pageCursor(last[0]) } : {}
360
+ };
361
+ }));
362
+ for (const extension of ["json", "yaml"]) {
363
+ const uri = url(`/openapi.${extension}`);
364
+ const mimeType = extension === "json" ? "application/json" : "application/yaml";
365
+ server.registerResource(`openapi-${extension}`, uri, {
366
+ title: `${application.title} OpenAPI (${extension.toUpperCase()})`,
367
+ description: "The service's OpenAPI document. Reading it grants no authority to run its operations.",
368
+ mimeType
369
+ }, () => answer(() => ({ contents: [{
370
+ uri,
371
+ mimeType,
372
+ text: contractText(extension)
373
+ }] })));
374
+ }
375
+ for (const guide of application.mcp?.guides ?? []) {
376
+ const uri = `${application.origin}/guides/${guide.name}`;
377
+ server.registerResource(guide.name, uri, {
378
+ title: guide.title,
379
+ mimeType: "text/markdown"
380
+ }, () => answer(() => ({ contents: [{
381
+ uri,
382
+ mimeType: "text/markdown",
383
+ text: guide.text
384
+ }] })));
385
+ server.registerPrompt(guide.name, {
386
+ title: guide.title,
387
+ description: "Read the integration usage guide."
388
+ }, () => answer(() => ({ messages: [{
389
+ role: "user",
390
+ content: {
391
+ type: "text",
392
+ text: guide.text
393
+ }
394
+ }] })));
395
+ }
396
+ if (skills.length) registerSkills(server, skills, answer);
397
+ return server;
398
+ }, { maxRequestBodySize: MAX_BODY_BYTES_CEILING }).fetch(request);
399
+ if (response.status >= 500) reportUnexpected(/* @__PURE__ */ new Error("MCP transport failure"), "mcp", requestId);
400
+ return response;
401
+ }
402
+ };
403
+ }
404
+
405
+ //#endregion
406
+ export { mcp };