@softure-ai/mcp-access 0.2.5 → 0.2.8

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 (65) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +121 -2
  3. package/dist/index.d.ts +8 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1 -1
  6. package/dist/messages/en.d.ts +8 -0
  7. package/dist/messages/en.d.ts.map +1 -1
  8. package/dist/messages/en.js +8 -0
  9. package/dist/messages/en.js.map +1 -1
  10. package/dist/messages/index.d.ts +8 -0
  11. package/dist/messages/index.d.ts.map +1 -1
  12. package/dist/server/action-tool.d.ts +6 -2
  13. package/dist/server/action-tool.d.ts.map +1 -1
  14. package/dist/server/action-tool.js +10 -3
  15. package/dist/server/action-tool.js.map +1 -1
  16. package/dist/server/index.d.ts +6 -2
  17. package/dist/server/index.d.ts.map +1 -1
  18. package/dist/server/index.js +6 -2
  19. package/dist/server/index.js.map +1 -1
  20. package/dist/server/server-factory.d.ts +31 -0
  21. package/dist/server/server-factory.d.ts.map +1 -0
  22. package/dist/server/server-factory.js +49 -0
  23. package/dist/server/server-factory.js.map +1 -0
  24. package/dist/server/server-info.d.ts +34 -0
  25. package/dist/server/server-info.d.ts.map +1 -0
  26. package/dist/server/server-info.js +30 -0
  27. package/dist/server/server-info.js.map +1 -0
  28. package/dist/server/strict-input.d.ts +17 -0
  29. package/dist/server/strict-input.d.ts.map +1 -0
  30. package/dist/server/strict-input.js +157 -0
  31. package/dist/server/strict-input.js.map +1 -0
  32. package/dist/server/tokens.d.ts +5 -0
  33. package/dist/server/tokens.d.ts.map +1 -1
  34. package/dist/server/tokens.js +10 -0
  35. package/dist/server/tokens.js.map +1 -1
  36. package/dist/server/tool-list.d.ts +35 -0
  37. package/dist/server/tool-list.d.ts.map +1 -0
  38. package/dist/server/tool-list.js +68 -0
  39. package/dist/server/tool-list.js.map +1 -0
  40. package/dist/server/tools.d.ts +40 -1
  41. package/dist/server/tools.d.ts.map +1 -1
  42. package/dist/server/tools.js +41 -3
  43. package/dist/server/tools.js.map +1 -1
  44. package/dist/testing/catalog.d.ts +8 -0
  45. package/dist/testing/catalog.d.ts.map +1 -1
  46. package/dist/testing/catalog.js +8 -19
  47. package/dist/testing/catalog.js.map +1 -1
  48. package/dist/testing/index.d.ts +1 -1
  49. package/dist/testing/index.d.ts.map +1 -1
  50. package/dist/testing/index.js +1 -1
  51. package/dist/testing/index.js.map +1 -1
  52. package/module.json +1 -1
  53. package/package.json +1 -1
  54. package/src/index.ts +1 -1
  55. package/src/messages/en.ts +9 -0
  56. package/src/server/action-tool.ts +15 -4
  57. package/src/server/index.ts +34 -1
  58. package/src/server/server-factory.ts +78 -0
  59. package/src/server/server-info.ts +76 -0
  60. package/src/server/strict-input.ts +191 -0
  61. package/src/server/tokens.ts +10 -0
  62. package/src/server/tool-list.ts +105 -0
  63. package/src/server/tools.ts +78 -5
  64. package/src/testing/catalog.ts +14 -23
  65. package/src/testing/index.ts +7 -1
@@ -1 +1 @@
1
- {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../src/testing/catalog.ts"],"names":[],"mappings":"AAAA,oGAAoG;AACpG,uGAAuG;AACvG,2FAA2F;AAC3F,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAIhE,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAW3D,MAAM,MAAM,GAAsB,EAAE,MAAM,EAAE,sCAAsC,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,eAAe,EAAE,CAAC;AAChI,MAAM,MAAM,GAAsB,EAAE,GAAG,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;AAEhE,2HAA2H;AAC3H,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,MAAqB,EAAE,YAA8B;IACnG,MAAM,OAAO,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC;IAClD,MA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QACxB,MAAM,IAAI,KAAK,CAAC,gGAAgG,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACzI,CAAC;AACH,CAAC;AAED,kGAAkG;AAClG,KAAK,UAAU,eAAe,CAAC,YAA8B,EAAE,QAA2B;IACxF,OAAO,CAAC,MAAM,eAAe,CAAC,GAAG,EAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACxF,CAAC;AAED,0HAA0H;AAC1H,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,YAA8B,EAAE,OAAgB;IAC3F,OAAO;QACL,IAAI,EAAE,gBAAgB,CAAC,MAAM,eAAe,CAAC,GAAG,EAAE,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,EAAE,OAAO,CAAC;QAClF,KAAK,EAAE,gBAAgB,CAAC,MAAM,eAAe,CAAC,GAAG,EAAE,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,EAAE,OAAO,CAAC;KACpF,CAAC;AACJ,CAAC"}
@@ -1,2 +1,2 @@
1
- export { expectToolCatalogMatchesServer, getToolCatalogDifferences, type ToolCatalogDifferences } from "./catalog.js";
1
+ export { expectToolCatalogMatchesServer, getToolCatalogDifferences, measureServedToolLists, type ServedToolLists, type ToolCatalogDifferences, } from "./catalog.js";
2
2
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,yBAAyB,EAAE,KAAK,sBAAsB,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,8BAA8B,EAC9B,yBAAyB,EACzB,sBAAsB,EACtB,KAAK,eAAe,EACpB,KAAK,sBAAsB,GAC5B,MAAM,cAAc,CAAC"}
@@ -1,3 +1,3 @@
1
1
  // `@softure-ai/mcp-access/testing`: checks for an app's own tests.
2
- export { expectToolCatalogMatchesServer, getToolCatalogDifferences } from "./catalog.js";
2
+ export { expectToolCatalogMatchesServer, getToolCatalogDifferences, measureServedToolLists, } from "./catalog.js";
3
3
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,OAAO,EAAE,8BAA8B,EAAE,yBAAyB,EAA+B,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA,mEAAmE;AACnE,OAAO,EACL,8BAA8B,EAC9B,yBAAyB,EACzB,sBAAsB,GAGvB,MAAM,cAAc,CAAC"}
package/module.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "mcp-access",
3
- "version": "0.2.5",
3
+ "version": "0.2.8",
4
4
  "dependsOn": { "security": "^0.2.0", "auth": "^0.2.0", "jobs": "^0.1.1?", "ops": "^0.2.0?" },
5
5
  "dbSchema": "mcp",
6
6
  "tables": ["access_tokens", "oauth_clients", "oauth_authorization_codes", "oauth_grants", "oauth_registration_window"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softure-ai/mcp-access",
3
- "version": "0.2.5",
3
+ "version": "0.2.8",
4
4
  "description": "SOFTURE AI MCP access module: hashed, scoped, expiring access tokens, a rate-limited Bearer endpoint around the app's MCP server factory, and a token page with client setup instructions for Next.js; tool result helpers with a safe error boundary, a stdio entry, a catalog parity check and the softure-mcp prune command.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/index.ts CHANGED
@@ -34,7 +34,7 @@ export const MCP_RATE_LIMIT_BUCKETS = {
34
34
  export const mcpAccess = defineModule({
35
35
  manifest: {
36
36
  id: MODULE_ID,
37
- version: "0.2.5",
37
+ version: "0.2.8",
38
38
  dependsOn: { security: "^0.2.0", auth: "^0.2.0", jobs: "^0.1.1?", ops: "^0.2.0?" },
39
39
  dbSchema: "mcp",
40
40
  tables: ["access_tokens", "oauth_clients", "oauth_authorization_codes", "oauth_grants", "oauth_registration_window"],
@@ -85,6 +85,15 @@ export const en = {
85
85
  nothingGranted: "No access was granted.",
86
86
  backToApp: "Back to the app ({target})",
87
87
  },
88
+ toolInput: {
89
+ unknownFields: "Unknown fields: {fields}. Accepted fields: {accepted}.",
90
+ noFields: "none",
91
+ fieldRenamed: "input.field_renamed: the field \"{field}\" is now \"{renamed}\". Send it as \"{renamed}\".",
92
+ },
93
+ serverInfoTool: {
94
+ description:
95
+ "Tells which build of this server answers: its name and version (the version changes whenever a tool changes), the release, the commit, when it was built and started, and the changelog when the app publishes one. Use it to check that a change is live.",
96
+ },
88
97
  errors: {
89
98
  "mcp-access": {
90
99
  name_required: "Give the token a name, so you can tell it from the others.",
@@ -1,7 +1,7 @@
1
1
  // A server action as a write tool: the tool's arguments become the form the action reads, so the tool
2
2
  // and the form share one validation path, and the action's error state becomes a tool error.
3
3
  import type { CallToolResult } from "@modelcontextprotocol/server";
4
- import { describeCode, toolError, toolResult, withToolErrors, type ToolErrorHints } from "./tools.js";
4
+ import { toolResult, withToolErrors, type ToolCaller, type ToolCallHook, type ToolErrorHints } from "./tools.js";
5
5
 
6
6
  /** The action, called with the form. A `useActionState` action is passed as `(form) => action(INITIAL, form)`. */
7
7
  export type FormActionHandler = (formData: FormData) => unknown;
@@ -11,8 +11,12 @@ export interface ActionToolOptions {
11
11
  readonly message?: string | ((state: unknown) => string);
12
12
  /** Texts per error code, as in `withToolErrors`. */
13
13
  readonly hints?: ToolErrorHints;
14
- /** The tool's name in the log line. */
14
+ /** The tool's name in the log line and in the `onToolCall` record. */
15
15
  readonly label?: string;
16
+ /** Called once after each call with its record, as in `withToolErrors`. */
17
+ readonly onToolCall?: ToolCallHook;
18
+ /** Who called, for the record, as in `withToolErrors`. */
19
+ readonly caller?: ToolCaller;
16
20
  }
17
21
 
18
22
  /** The tool callback for `server.registerTool(name, { inputSchema }, actionTool(handler))`. */
@@ -23,11 +27,18 @@ export function actionTool(handler: FormActionHandler, options: ActionToolOption
23
27
  async () => {
24
28
  const state = await handler(toFormData(args));
25
29
  const error = readErrorCode(state);
26
- if (error !== null) return toolError(describeCode(error, hints));
30
+ // As a core result, so withToolErrors answers it through the hints and records its code.
31
+ if (error !== null) return { ok: false, error };
27
32
  if (options.message === undefined) return toolResult(state);
28
33
  return toolResult(typeof options.message === "string" ? options.message : options.message(state));
29
34
  },
30
- { hints, ...(options.label === undefined ? {} : { label: options.label }) },
35
+ {
36
+ hints,
37
+ args,
38
+ ...(options.label === undefined ? {} : { label: options.label }),
39
+ ...(options.onToolCall === undefined ? {} : { onToolCall: options.onToolCall }),
40
+ ...(options.caller === undefined ? {} : { caller: options.caller }),
41
+ },
31
42
  );
32
43
  }
33
44
 
@@ -92,6 +92,7 @@ export {
92
92
  issueAccessToken,
93
93
  listAccessTokens,
94
94
  pruneAccessTokens,
95
+ findTokenClientName,
95
96
  revokeAccessToken,
96
97
  verifyAccessToken,
97
98
  type IssueAccessTokenInput,
@@ -101,4 +102,36 @@ export {
101
102
  type RevokeAccessTokenInput,
102
103
  type VerifiedAccessToken,
103
104
  } from "./tokens.js";
104
- export { toolError, toolResult, withToolErrors, type ToolErrorHints, type ToolErrorOptions } from "./tools.js";
105
+ export { createMcpServerFactory, type McpServerFactoryOptions } from "./server-factory.js";
106
+ export {
107
+ registerServerInfoTool,
108
+ SERVER_INFO_TOOL_NAME,
109
+ type McpBuildInfo,
110
+ type RegisterServerInfoToolOptions,
111
+ type ServedServerInfo,
112
+ type ServerInfoAnswer,
113
+ type ServerInfoToolOptions,
114
+ } from "./server-info.js";
115
+ export { toStrictToolInput, withStrictToolInput, type StrictToolInputMessages, type StrictToolInputOptions } from "./strict-input.js";
116
+ export {
117
+ DEFAULT_TOOL_LIST_RELEASE,
118
+ describeToolList,
119
+ fingerprintToolList,
120
+ listServedTools,
121
+ measureToolList,
122
+ type MeasureToolListOptions,
123
+ type RegisterTools,
124
+ type ServedTool,
125
+ type ToolListMeasurement,
126
+ } from "./tool-list.js";
127
+ export {
128
+ toolError,
129
+ toolResult,
130
+ withToolErrors,
131
+ type ToolCaller,
132
+ type ToolCallHook,
133
+ type ToolCallOutcome,
134
+ type ToolCallRecord,
135
+ type ToolErrorHints,
136
+ type ToolErrorOptions,
137
+ } from "./tools.js";
@@ -0,0 +1,78 @@
1
+ // The app's MCP server factory with a version that follows its tool list. The tools are measured once
2
+ // per access level (a read-only token sees fewer tools) on a recording server, and each request's
3
+ // server answers `initialize` with that level's version, so a client drops its cached `tools/list`
4
+ // whenever a release changes a tool. The factory plugs into `createMcpEndpoint`, `serveMcpStdio` and
5
+ // the catalog check like a hand-written one.
6
+ //
7
+ // export const createServer = createMcpServerFactory({
8
+ // name: "acme",
9
+ // registerTools: (server, identity) => registerNoteTools(server, identity),
10
+ // });
11
+ import { McpServer, type McpServerOptions } from "@modelcontextprotocol/server";
12
+ import type { McpServerIdentity } from "../contract.js";
13
+ import type { McpServerFactory } from "./endpoint.js";
14
+ import { withStrictToolInput, type StrictToolInputOptions } from "./strict-input.js";
15
+ import { registerServerInfoTool, type ServerInfoToolOptions } from "./server-info.js";
16
+ import { measureToolList, type ToolListMeasurement } from "./tool-list.js";
17
+
18
+ export interface McpServerFactoryOptions {
19
+ /** `serverInfo.name`. */
20
+ readonly name: string;
21
+ /** `serverInfo.title`, the name a client shows. */
22
+ readonly title?: string;
23
+ /** The `MAJOR.MINOR.PATCH` before `-tools-`. Default: `1.0.0`. */
24
+ readonly release?: string;
25
+ /** A fixed `serverInfo.version` instead of the measured one. */
26
+ readonly version?: string;
27
+ readonly serverOptions?: McpServerOptions;
28
+ /**
29
+ * Registers the tools for one request. The tool list may depend on `identity.canWrite` only: it is
30
+ * measured once per access level. A list that depends on the account needs `measureToolList` per call.
31
+ */
32
+ readonly registerTools: (server: McpServer, identity: McpServerIdentity) => unknown;
33
+ /** Every tool's input is strict (`withStrictToolInput`), on the served and the measured server alike. */
34
+ readonly strictToolInput?: boolean | StrictToolInputOptions;
35
+ /**
36
+ * Adds the read-only `get_server_info` tool for every access level: the build info (pass `readBuildInfo` of
37
+ * `@softure-ai/ops/server`) with the served name and version. Off by default.
38
+ */
39
+ readonly serverInfoTool?: ServerInfoToolOptions;
40
+ }
41
+
42
+ /** An `McpServerFactory` whose servers carry the tool list's version for the identity's access level. */
43
+ export function createMcpServerFactory(options: McpServerFactoryOptions): McpServerFactory {
44
+ const strictOptions = options.strictToolInput === true ? {} : options.strictToolInput === false ? undefined : options.strictToolInput;
45
+ // The served version reaches `get_server_info` here; the recording server registers it with a placeholder, since
46
+ // its handler never runs there and the version is not part of the listed tool.
47
+ const registerTools = async (server: McpServer, identity: McpServerIdentity, version = ""): Promise<void> => {
48
+ const target = strictOptions === undefined ? server : withStrictToolInput(server, strictOptions);
49
+ await options.registerTools(target, identity);
50
+ if (options.serverInfoTool !== undefined) registerServerInfoTool(target, { ...options.serverInfoTool, server: { name: options.name, version } });
51
+ };
52
+ const measurements = new Map<boolean, Promise<ToolListMeasurement>>();
53
+
54
+ // The promise is cached, so parallel first requests measure once; a failed measurement is dropped so
55
+ // the next request tries again instead of failing for good.
56
+ const measure = (identity: McpServerIdentity): Promise<ToolListMeasurement> => {
57
+ const cached = measurements.get(identity.canWrite);
58
+ if (cached !== undefined) return cached;
59
+ const measurement = measureToolList((server) => registerTools(server, identity), {
60
+ ...(options.release === undefined ? {} : { release: options.release }),
61
+ name: options.name,
62
+ ...(options.serverOptions === undefined ? {} : { serverOptions: options.serverOptions }),
63
+ });
64
+ measurements.set(identity.canWrite, measurement);
65
+ void measurement.catch(() => measurements.delete(identity.canWrite));
66
+ return measurement;
67
+ };
68
+
69
+ return async (identity) => {
70
+ const version = options.version ?? (await measure(identity)).toolListVersion;
71
+ const server = new McpServer(
72
+ { name: options.name, version, ...(options.title === undefined ? {} : { title: options.title }) },
73
+ options.serverOptions,
74
+ );
75
+ await registerTools(server, identity, version);
76
+ return server;
77
+ };
78
+ }
@@ -0,0 +1,76 @@
1
+ // The `get_server_info` tool (#885): an assistant checks a "done" against production in one call. It answers the
2
+ // public facts of the ops build info route (release, commit, build and start times, the optional changelog) and the
3
+ // name and version the server answered at `initialize`, which follows the tool list. It reads no user data.
4
+ //
5
+ // The app passes the build info reader, so `/server` never loads `@softure-ai/ops` (an optional peer):
6
+ //
7
+ // import { readBuildInfo } from "@softure-ai/ops/server";
8
+ // createMcpServerFactory({ name: "acme", registerTools, serverInfoTool: { buildInfo: () => readBuildInfo() } });
9
+ import type { McpServer } from "@modelcontextprotocol/server";
10
+ import { errorLogLabel } from "@softure-ai/core";
11
+ import { z } from "zod";
12
+ import { en } from "../messages/en.js";
13
+ import { toolResult } from "./tools.js";
14
+
15
+ export const SERVER_INFO_TOOL_NAME = "get_server_info";
16
+
17
+ /** The build info of `@softure-ai/ops` (`readBuildInfo()`), typed by shape so mcp-access does not import ops. */
18
+ export interface McpBuildInfo {
19
+ readonly release: string | null;
20
+ readonly commit: string | null;
21
+ readonly builtAt: string | null;
22
+ readonly startedAt: string;
23
+ }
24
+
25
+ export interface ServerInfoToolOptions {
26
+ /** The build info, e.g. `() => readBuildInfo()` from `@softure-ai/ops/server` with the route's options. */
27
+ readonly buildInfo: () => McpBuildInfo | Promise<McpBuildInfo>;
28
+ /** The changelog the build info route answers, when the app passes one there. Only what is public. */
29
+ readonly changelog?: () => unknown;
30
+ /** Default: `serverInfoTool.description` of the module dictionary. */
31
+ readonly description?: string;
32
+ }
33
+
34
+ /** What `initialize` answers as `serverInfo`. */
35
+ export interface ServedServerInfo {
36
+ readonly name: string;
37
+ readonly version: string;
38
+ }
39
+
40
+ export interface RegisterServerInfoToolOptions extends ServerInfoToolOptions {
41
+ /** The name and version the server answers at `initialize`; `createMcpServerFactory` passes them in. */
42
+ readonly server: ServedServerInfo;
43
+ }
44
+
45
+ /** The tool's answer: the served name and version, the build info and, with a provider, the changelog. */
46
+ export type ServerInfoAnswer = McpBuildInfo & { readonly server: ServedServerInfo; readonly changelog?: unknown };
47
+
48
+ /** Registers `get_server_info`: no input fields, read only. A failing `buildInfo` reaches the SDK, which answers a tool error. */
49
+ export function registerServerInfoTool(server: McpServer, options: RegisterServerInfoToolOptions): void {
50
+ server.registerTool(
51
+ SERVER_INFO_TOOL_NAME,
52
+ {
53
+ description: options.description ?? en.serverInfoTool.description,
54
+ // An empty object rather than no schema, so strict input refuses a field sent to it.
55
+ inputSchema: z.object({}),
56
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
57
+ },
58
+ async () => toolResult(await readServerInfo(options)),
59
+ );
60
+ }
61
+
62
+ async function readServerInfo(options: RegisterServerInfoToolOptions): Promise<ServerInfoAnswer> {
63
+ const { release, commit, builtAt, startedAt } = await options.buildInfo();
64
+ const answer: ServerInfoAnswer = { server: { name: options.server.name, version: options.server.version }, release, commit, builtAt, startedAt };
65
+ return options.changelog === undefined ? answer : { ...answer, changelog: await readChangelog(options.changelog) };
66
+ }
67
+
68
+ /** As the build info route: a failing provider answers `null` and logs the error class, so the build info still answers. */
69
+ async function readChangelog(provider: () => unknown): Promise<unknown> {
70
+ try {
71
+ return (await provider()) ?? null;
72
+ } catch (error) {
73
+ console.error(`get_server_info: the changelog provider failed: ${errorLogLabel(error)}`);
74
+ return null;
75
+ }
76
+ }
@@ -0,0 +1,191 @@
1
+ // Strict tool input. zod objects strip unknown keys, so a tool call with a misspelt field (`notes` for
2
+ // `note`) or a field of a newer tool list answers as a write that worked while the value was dropped.
3
+ // `withStrictToolInput` rewrites every input schema once, at registration: each object refuses a field
4
+ // it does not know and names the ones it accepts, a field sent under its old name is refused with the
5
+ // stable code `input.field_renamed`, and boolean and number fields also take their exact text (a client
6
+ // on an older tool list sends a field it does not know as text). The SDK validates before the handler
7
+ // runs, so a refused call saves nothing.
8
+ //
9
+ // const server = withStrictToolInput(new McpServer({ name: "acme", version }), { renamedFields: { notes: "note" } });
10
+ import type { McpServer } from "@modelcontextprotocol/server";
11
+ import { formatMessage } from "@softure-ai/core";
12
+ import { z } from "zod";
13
+ import type * as core from "zod/v4/core";
14
+ import { en } from "../messages/en.js";
15
+
16
+ /** The texts of a refused field: `toolInput` of the module dictionary (`getMcpAccessMessages(config).toolInput`). */
17
+ export type StrictToolInputMessages = typeof en.toolInput;
18
+
19
+ export interface StrictToolInputOptions {
20
+ /** Old field name → new field name, refused as `input.field_renamed` wherever an object accepts the new name. */
21
+ readonly renamedFields?: Readonly<Record<string, string>>;
22
+ /** Boolean fields also take `"true"`/`"false"` and number fields a number written as text. Default: `true`. */
23
+ readonly coerceTextScalars?: boolean;
24
+ /** Default: the module's English dictionary. */
25
+ readonly messages?: StrictToolInputMessages;
26
+ }
27
+
28
+ /** A JSON number literal: no spaces, no hex, no empty text. */
29
+ const NUMBER_TEXT = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
30
+
31
+ const strictServers = new WeakSet<McpServer>();
32
+
33
+ type ToolConfig = Readonly<Record<string, unknown>> & { readonly inputSchema?: unknown };
34
+ type RegisterTool = (name: string, config: ToolConfig, callback: unknown) => unknown;
35
+
36
+ /** Makes every tool registered on the server from now on strict; wrapping a server twice changes nothing. */
37
+ export function withStrictToolInput<Server extends McpServer>(server: Server, options: StrictToolInputOptions = {}): Server {
38
+ if (strictServers.has(server)) return server;
39
+ // The SDK's overloads only differ in how the schema is typed; at runtime it is one method.
40
+ const register = server.registerTool.bind(server) as unknown as RegisterTool;
41
+ const registerStrict: RegisterTool = (name, config, callback) =>
42
+ register(name, config.inputSchema === undefined ? config : { ...config, inputSchema: toStrictToolInput(config.inputSchema, options) }, callback);
43
+ Object.defineProperty(server, "registerTool", { value: registerStrict, configurable: true, writable: true });
44
+ strictServers.add(server);
45
+ return server;
46
+ }
47
+
48
+ /** The strict form of a tool's input schema: a zod 4 schema or raw shape is rewritten, anything else passes unchanged. */
49
+ export function toStrictToolInput(schema: unknown, options: StrictToolInputOptions = {}): unknown {
50
+ const zodSchema = isZodSchema(schema) ? schema : isRawShape(schema) ? z.object(schema) : null;
51
+ if (zodSchema === null) return schema;
52
+ const rewriter = new StrictRewriter({
53
+ renamedFields: options.renamedFields ?? {},
54
+ coerceTextScalars: options.coerceTextScalars ?? true,
55
+ messages: options.messages ?? en.toolInput,
56
+ });
57
+ return rewriter.rewrite(zodSchema);
58
+ }
59
+
60
+ function isZodSchema(value: unknown): value is core.$ZodType {
61
+ return typeof value === "object" && value !== null && "_zod" in value;
62
+ }
63
+
64
+ function isRawShape(value: unknown): value is Record<string, core.$ZodType> {
65
+ if (typeof value !== "object" || value === null || Object.getPrototypeOf(value) !== Object.prototype) return false;
66
+ return Object.values(value).every(isZodSchema);
67
+ }
68
+
69
+ type RewriteSettings = Required<StrictToolInputOptions>;
70
+
71
+ /** A schema node as the rewriter reads it: its kind and the parts it rewrites. */
72
+ type AnyDef = core.$ZodTypeDef & Record<string, unknown>;
73
+
74
+ class StrictRewriter {
75
+ // The same node (a shared field, a recursive `z.lazy`) is rewritten once.
76
+ private readonly rewritten = new Map<core.$ZodType, core.$ZodType>();
77
+
78
+ constructor(private readonly settings: RewriteSettings) {}
79
+
80
+ rewrite(schema: core.$ZodType): core.$ZodType {
81
+ const known = this.rewritten.get(schema);
82
+ if (known !== undefined) return known;
83
+ const result = this.rewriteNode(schema);
84
+ this.rewritten.set(schema, result);
85
+ return result;
86
+ }
87
+
88
+ private rewriteNode(schema: core.$ZodType): core.$ZodType {
89
+ const def = schema._zod.def as AnyDef;
90
+ switch (def.type) {
91
+ case "object":
92
+ return this.rewriteObject(schema as core.$ZodObject);
93
+ case "array":
94
+ return this.cloneWith(schema, { element: this.rewrite(def.element as core.$ZodType) });
95
+ case "optional":
96
+ case "nullable":
97
+ case "default":
98
+ case "prefault":
99
+ case "nonoptional":
100
+ case "readonly":
101
+ case "catch":
102
+ return this.cloneWith(schema, { innerType: this.rewrite(def.innerType as core.$ZodType) });
103
+ case "union":
104
+ return this.cloneWith(schema, { options: (def.options as core.$ZodType[]).map((option) => this.rewrite(option)) });
105
+ case "intersection":
106
+ return this.cloneWith(schema, { left: this.rewrite(def.left as core.$ZodType), right: this.rewrite(def.right as core.$ZodType) });
107
+ case "record":
108
+ return this.cloneWith(schema, { valueType: this.rewrite(def.valueType as core.$ZodType) });
109
+ case "tuple":
110
+ return this.cloneWith(schema, {
111
+ items: (def.items as core.$ZodType[]).map((item) => this.rewrite(item)),
112
+ rest: def.rest === null ? null : this.rewrite(def.rest as core.$ZodType),
113
+ });
114
+ case "pipe":
115
+ return this.rewritePipe(schema, def);
116
+ case "lazy": {
117
+ const getter = def.getter as () => core.$ZodType;
118
+ return this.cloneWith(schema, { getter: () => this.rewrite(getter()) });
119
+ }
120
+ case "boolean":
121
+ return this.settings.coerceTextScalars && def.coerce !== true ? z.preprocess(readBooleanText, schema) : schema;
122
+ case "number":
123
+ return this.settings.coerceTextScalars && def.coerce !== true ? z.preprocess(readNumberText, schema) : schema;
124
+ default:
125
+ return schema;
126
+ }
127
+ }
128
+
129
+ /** Only the input side: `in`, or `out` after a preprocess (whose `in` is the transform). */
130
+ private rewritePipe(schema: core.$ZodType, def: AnyDef): core.$ZodType {
131
+ const input = def.in as core.$ZodType;
132
+ if (input._zod.traits.has("$ZodTransform")) return this.cloneWith(schema, { out: this.rewrite(def.out as core.$ZodType) });
133
+ return this.cloneWith(schema, { in: this.rewrite(input) });
134
+ }
135
+
136
+ private rewriteObject(schema: core.$ZodObject): core.$ZodType {
137
+ const def = schema._zod.def;
138
+ const shape = Object.fromEntries(Object.entries(def.shape).map(([name, field]) => [name, this.rewrite(field)]));
139
+ // An object with its own catchall (`looseObject`, `.catchall(x)`) accepts extra fields on purpose.
140
+ if (def.catchall !== undefined && def.catchall._zod.def.type !== "never") return this.cloneWith(schema, { shape });
141
+ // The object's own map, read for any issue: its parameter type is narrowed to the issues an object raises.
142
+ const ownError = def.error as core.$ZodErrorMap | undefined;
143
+ const describe = (issue: core.$ZodRawIssue): string | undefined => describeUnknownFields(issue, Object.keys(shape), this.settings);
144
+ const error: core.$ZodErrorMap = (issue) => describe(issue) ?? ownError?.(issue);
145
+ return this.cloneWith(schema, { shape, catchall: z.never(), error });
146
+ }
147
+
148
+ /** A copy of the node with some parts replaced; its description and other metadata stay with it. */
149
+ private cloneWith(schema: core.$ZodType, parts: Record<string, unknown>): core.$ZodType {
150
+ const copy = (schema as unknown as z.ZodType).clone({ ...schema._zod.def, ...parts });
151
+ const meta = z.globalRegistry.get(schema);
152
+ if (meta !== undefined) {
153
+ // An id names one schema in the JSON Schema output; the copy replaces the original, so it may not carry it twice.
154
+ const rest = { ...meta };
155
+ delete rest.id;
156
+ z.globalRegistry.add(copy, rest);
157
+ }
158
+ return copy;
159
+ }
160
+ }
161
+
162
+ /** The text for an object's unknown fields: renamed ones first, then the rest with the fields it accepts. */
163
+ function describeUnknownFields(issue: core.$ZodRawIssue, accepted: readonly string[], settings: RewriteSettings): string | undefined {
164
+ if (issue.code !== "unrecognized_keys") return undefined;
165
+ const { messages, renamedFields } = settings;
166
+ const renamed: string[] = [];
167
+ const unknown: string[] = [];
168
+ for (const field of issue.keys) {
169
+ const newName = Object.hasOwn(renamedFields, field) ? renamedFields[field] : undefined;
170
+ if (newName !== undefined && accepted.includes(newName)) renamed.push(formatMessage(messages.fieldRenamed, { field, renamed: newName }));
171
+ else unknown.push(field);
172
+ }
173
+ if (unknown.length > 0) {
174
+ renamed.push(formatMessage(messages.unknownFields, { fields: quoteAll(unknown), accepted: accepted.length > 0 ? quoteAll(accepted) : messages.noFields }));
175
+ }
176
+ return renamed.join(" ");
177
+ }
178
+
179
+ function quoteAll(names: readonly string[]): string {
180
+ return names.map((name) => JSON.stringify(name)).join(", ");
181
+ }
182
+
183
+ function readBooleanText(value: unknown): unknown {
184
+ if (value === "true") return true;
185
+ if (value === "false") return false;
186
+ return value;
187
+ }
188
+
189
+ function readNumberText(value: unknown): unknown {
190
+ return typeof value === "string" && NUMBER_TEXT.test(value) ? Number(value) : value;
191
+ }
@@ -159,6 +159,16 @@ export interface VerifiedAccessToken {
159
159
  readonly grantId: string | null;
160
160
  }
161
161
 
162
+ /**
163
+ * A token's name, the client it was issued for ("Laptop", an OAuth client's name), for a record of tool calls:
164
+ * `null` for an id that is not a stored token's (the stdio id, a pruned or unknown token).
165
+ */
166
+ export async function findTokenClientName(ctx: McpAccessContext, tokenId: string): Promise<string | null> {
167
+ if (!UUID_SHAPE.test(tokenId)) return null;
168
+ const [row] = await ctx.db.select({ name: accessTokens.name }).from(accessTokens).where(eq(accessTokens.id, tokenId));
169
+ return row?.name ?? null;
170
+ }
171
+
162
172
  /**
163
173
  * The identity behind a token, or null for anything unknown, revoked or expired: the caller cannot
164
174
  * tell which, so a guess learns nothing. The expiry sits in the query, so no code path can forget
@@ -0,0 +1,105 @@
1
+ // The server version that follows the tool list. MCP clients keep a cached `tools/list` until the
2
+ // version they read at `initialize` changes, so a release that adds a tool or changes a schema under
3
+ // the same version leaves the assistant on the old schemas. `measureToolList` fingerprints the list
4
+ // as the client reads it, `<release>-tools-<12 hex>`: a semver prerelease, since comparisons ignore
5
+ // build metadata. The same registrations always give the same version.
6
+ import { createHash } from "node:crypto";
7
+ import { createMcpHandler, McpServer, METHOD_NOT_FOUND, type McpServerOptions, type Server } from "@modelcontextprotocol/server";
8
+
9
+ /** The release part when none is given. */
10
+ export const DEFAULT_TOOL_LIST_RELEASE = "1.0.0";
11
+
12
+ /** Hex digits of the fingerprint in the version. */
13
+ const FINGERPRINT_LENGTH = 12;
14
+ const RELEASE_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
15
+
16
+ /** What a client reads from `tools/list`: one entry per tool, as JSON. */
17
+ export type ServedTool = Readonly<Record<string, unknown>> & { readonly name: string };
18
+
19
+ export interface ToolListMeasurement {
20
+ /** `<release>-tools-<12 hex>`, for `serverInfo.version`. */
21
+ readonly toolListVersion: string;
22
+ readonly toolCount: number;
23
+ }
24
+
25
+ /** Registers the app's tools on the server it is given, e.g. `(server) => registerNoteTools(server, identity)`. */
26
+ export type RegisterTools = (server: McpServer) => unknown;
27
+
28
+ export interface MeasureToolListOptions {
29
+ /** The `MAJOR.MINOR.PATCH` before `-tools-`. Default: `1.0.0`. */
30
+ readonly release?: string;
31
+ /** The served server's name, so the recording server is shaped like it. Default: `tool-list`. */
32
+ readonly name?: string;
33
+ /** The served server's options (capabilities, instructions), for the same reason. */
34
+ readonly serverOptions?: McpServerOptions;
35
+ }
36
+
37
+ /**
38
+ * Registers the tools on a recording server shaped like the served one, lists them the way the endpoint
39
+ * serves them and returns the version with the tool count. Any change of a tool's name, title,
40
+ * description, annotations or input or output schema changes the version; the order of registration does not.
41
+ */
42
+ export async function measureToolList(registerTools: RegisterTools, options: MeasureToolListOptions = {}): Promise<ToolListMeasurement> {
43
+ const release = options.release ?? DEFAULT_TOOL_LIST_RELEASE;
44
+ assertRelease(release);
45
+ const server = new McpServer({ name: options.name ?? "tool-list", version: release }, options.serverOptions);
46
+ await registerTools(server);
47
+ return describeToolList(await listServedTools(() => server), release);
48
+ }
49
+
50
+ /** The version and count for a listed tool set. */
51
+ export function describeToolList(tools: readonly ServedTool[], release: string = DEFAULT_TOOL_LIST_RELEASE): ToolListMeasurement {
52
+ assertRelease(release);
53
+ return { toolListVersion: `${release}-tools-${fingerprintToolList(tools)}`, toolCount: tools.length };
54
+ }
55
+
56
+ /** The first 12 hex digits of a sha256 over the tools in name order, each as canonical JSON (keys sorted at every level). */
57
+ export function fingerprintToolList(tools: readonly ServedTool[]): string {
58
+ const ordered = [...tools].sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
59
+ return createHash("sha256").update(toCanonicalJson(ordered)).digest("hex").slice(0, FINGERPRINT_LENGTH);
60
+ }
61
+
62
+ /** Every tool a fresh server from the factory lists (none when it registered none), asked with one stateless `tools/list` as the endpoint serves it. */
63
+ export async function listServedTools(createServer: () => McpServer | Server | Promise<McpServer | Server>): Promise<ServedTool[]> {
64
+ const handler = createMcpHandler(createServer, { responseMode: "json" });
65
+ const response = await handler.fetch(
66
+ new Request("http://localhost/api/mcp", {
67
+ method: "POST",
68
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },
69
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }),
70
+ }),
71
+ );
72
+ const answer = readAnswer(await response.text());
73
+ // A server that registered no tool declares no tools capability, so it does not know the method.
74
+ if (answer.error?.code === METHOD_NOT_FOUND) return [];
75
+ if (answer.result?.tools === undefined) {
76
+ throw new Error(`@softure-ai/mcp-access: listing the server's tools failed: ${typeof answer.error?.message === "string" ? answer.error.message : `HTTP ${String(response.status)}`}`);
77
+ }
78
+ return answer.result.tools.filter((tool): tool is ServedTool => typeof tool.name === "string" && tool.name !== "");
79
+ }
80
+
81
+ interface ToolsListAnswer {
82
+ readonly result?: { readonly tools?: readonly (Readonly<Record<string, unknown>> & { readonly name?: unknown })[] };
83
+ readonly error?: { readonly code?: unknown; readonly message?: unknown };
84
+ }
85
+
86
+ /** The JSON-RPC answer, sent as JSON or as one SSE `message` event. */
87
+ function readAnswer(body: string): ToolsListAnswer {
88
+ const data = body.startsWith("event:") ? (body.split("\n").find((line) => line.startsWith("data: "))?.slice("data: ".length) ?? "null") : body;
89
+ return (JSON.parse(data) ?? {}) as ToolsListAnswer;
90
+ }
91
+
92
+ function toCanonicalJson(value: unknown): string {
93
+ return JSON.stringify(value, (_key, entry: unknown) =>
94
+ entry !== null && typeof entry === "object" && !Array.isArray(entry)
95
+ ? Object.fromEntries(Object.entries(entry).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)))
96
+ : entry,
97
+ );
98
+ }
99
+
100
+ /** A release that is not `MAJOR.MINOR.PATCH` would make an invalid version: a setup bug, thrown. */
101
+ function assertRelease(release: string): void {
102
+ if (!RELEASE_PATTERN.test(release)) {
103
+ throw new Error(`@softure-ai/mcp-access: the tool list release must be MAJOR.MINOR.PATCH, got "${release}"`);
104
+ }
105
+ }