@stigmer/mcp-server 3.2.3 → 3.4.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 (179) hide show
  1. package/README.md +60 -13
  2. package/cli/mcp-server-stigmer.js +13 -9
  3. package/config.d.ts +12 -0
  4. package/config.d.ts.map +1 -1
  5. package/config.js +5 -0
  6. package/config.js.map +1 -1
  7. package/domains/agentexecutions/approve.d.ts +9 -0
  8. package/domains/agentexecutions/approve.d.ts.map +1 -0
  9. package/domains/agentexecutions/approve.js +46 -0
  10. package/domains/agentexecutions/approve.js.map +1 -0
  11. package/domains/agentexecutions/fetch.d.ts +28 -0
  12. package/domains/agentexecutions/fetch.d.ts.map +1 -0
  13. package/domains/agentexecutions/fetch.js +82 -0
  14. package/domains/agentexecutions/fetch.js.map +1 -0
  15. package/domains/agentexecutions/run.d.ts +27 -0
  16. package/domains/agentexecutions/run.d.ts.map +1 -0
  17. package/domains/agentexecutions/run.js +87 -0
  18. package/domains/agentexecutions/run.js.map +1 -0
  19. package/domains/agentexecutions/tools.d.ts +5 -0
  20. package/domains/agentexecutions/tools.d.ts.map +1 -0
  21. package/domains/agentexecutions/tools.js +97 -0
  22. package/domains/agentexecutions/tools.js.map +1 -0
  23. package/domains/datastores/apply.d.ts +4 -0
  24. package/domains/datastores/apply.d.ts.map +1 -0
  25. package/domains/datastores/apply.js +28 -0
  26. package/domains/datastores/apply.js.map +1 -0
  27. package/domains/datastores/delete.d.ts +3 -0
  28. package/domains/datastores/delete.d.ts.map +1 -0
  29. package/domains/datastores/delete.js +38 -0
  30. package/domains/datastores/delete.js.map +1 -0
  31. package/domains/datastores/fetch.d.ts +3 -0
  32. package/domains/datastores/fetch.d.ts.map +1 -0
  33. package/domains/datastores/fetch.js +23 -0
  34. package/domains/datastores/fetch.js.map +1 -0
  35. package/domains/datastores/resources.d.ts +5 -0
  36. package/domains/datastores/resources.d.ts.map +1 -0
  37. package/domains/datastores/resources.js +16 -0
  38. package/domains/datastores/resources.js.map +1 -0
  39. package/domains/datastores/tools.d.ts +5 -0
  40. package/domains/datastores/tools.d.ts.map +1 -0
  41. package/domains/datastores/tools.js +46 -0
  42. package/domains/datastores/tools.js.map +1 -0
  43. package/domains/environments/apply.d.ts +4 -0
  44. package/domains/environments/apply.d.ts.map +1 -0
  45. package/domains/environments/apply.js +30 -0
  46. package/domains/environments/apply.js.map +1 -0
  47. package/domains/environments/delete.d.ts +3 -0
  48. package/domains/environments/delete.d.ts.map +1 -0
  49. package/domains/environments/delete.js +36 -0
  50. package/domains/environments/delete.js.map +1 -0
  51. package/domains/environments/fetch.d.ts +6 -0
  52. package/domains/environments/fetch.d.ts.map +1 -0
  53. package/domains/environments/fetch.js +30 -0
  54. package/domains/environments/fetch.js.map +1 -0
  55. package/domains/environments/resources.d.ts +5 -0
  56. package/domains/environments/resources.d.ts.map +1 -0
  57. package/domains/environments/resources.js +16 -0
  58. package/domains/environments/resources.js.map +1 -0
  59. package/domains/environments/tools.d.ts +5 -0
  60. package/domains/environments/tools.d.ts.map +1 -0
  61. package/domains/environments/tools.js +51 -0
  62. package/domains/environments/tools.js.map +1 -0
  63. package/domains/executions/cancel.d.ts +9 -0
  64. package/domains/executions/cancel.d.ts.map +1 -0
  65. package/domains/executions/cancel.js +114 -0
  66. package/domains/executions/cancel.js.map +1 -0
  67. package/domains/executions/tools.d.ts +5 -0
  68. package/domains/executions/tools.d.ts.map +1 -0
  69. package/domains/executions/tools.js +28 -0
  70. package/domains/executions/tools.js.map +1 -0
  71. package/domains/records/calls.d.ts +48 -0
  72. package/domains/records/calls.d.ts.map +1 -0
  73. package/domains/records/calls.js +118 -0
  74. package/domains/records/calls.js.map +1 -0
  75. package/domains/records/errors.d.ts +24 -0
  76. package/domains/records/errors.d.ts.map +1 -0
  77. package/domains/records/errors.js +79 -0
  78. package/domains/records/errors.js.map +1 -0
  79. package/domains/records/tools.d.ts +7 -0
  80. package/domains/records/tools.d.ts.map +1 -0
  81. package/domains/records/tools.js +139 -0
  82. package/domains/records/tools.js.map +1 -0
  83. package/domains/resourceuri.d.ts.map +1 -1
  84. package/domains/resourceuri.js +2 -0
  85. package/domains/resourceuri.js.map +1 -1
  86. package/domains/search/tools.d.ts.map +1 -1
  87. package/domains/search/tools.js +10 -7
  88. package/domains/search/tools.js.map +1 -1
  89. package/domains/skills/tools.d.ts.map +1 -1
  90. package/domains/skills/tools.js +25 -1
  91. package/domains/skills/tools.js.map +1 -1
  92. package/domains/skills/versions.d.ts +9 -0
  93. package/domains/skills/versions.d.ts.map +1 -0
  94. package/domains/skills/versions.js +31 -0
  95. package/domains/skills/versions.js.map +1 -0
  96. package/domains/workflowexecutions/approvals.d.ts +17 -0
  97. package/domains/workflowexecutions/approvals.d.ts.map +1 -0
  98. package/domains/workflowexecutions/approvals.js +61 -0
  99. package/domains/workflowexecutions/approvals.js.map +1 -0
  100. package/domains/workflowexecutions/run.d.ts +12 -0
  101. package/domains/workflowexecutions/run.d.ts.map +1 -0
  102. package/domains/workflowexecutions/run.js +69 -0
  103. package/domains/workflowexecutions/run.js.map +1 -0
  104. package/domains/workflowexecutions/tools.d.ts.map +1 -1
  105. package/domains/workflowexecutions/tools.js +89 -6
  106. package/domains/workflowexecutions/tools.js.map +1 -1
  107. package/domains/workflows/tools.d.ts.map +1 -1
  108. package/domains/workflows/tools.js +69 -5
  109. package/domains/workflows/tools.js.map +1 -1
  110. package/domains/workflows/versions.d.ts +29 -0
  111. package/domains/workflows/versions.d.ts.map +1 -0
  112. package/domains/workflows/versions.js +99 -0
  113. package/domains/workflows/versions.js.map +1 -0
  114. package/gen/agent.d.ts +56 -0
  115. package/gen/agent.d.ts.map +1 -1
  116. package/gen/agent.js +24 -1
  117. package/gen/agent.js.map +1 -1
  118. package/gen/datastore.d.ts +861 -0
  119. package/gen/datastore.d.ts.map +1 -0
  120. package/gen/datastore.js +267 -0
  121. package/gen/datastore.js.map +1 -0
  122. package/gen/environment.d.ts +77 -0
  123. package/gen/environment.d.ts.map +1 -0
  124. package/gen/environment.js +62 -0
  125. package/gen/environment.js.map +1 -0
  126. package/gen/workflow.d.ts +4 -4
  127. package/index.d.ts +2 -2
  128. package/index.d.ts.map +1 -1
  129. package/index.js +4 -4
  130. package/index.js.map +1 -1
  131. package/package.json +3 -3
  132. package/server.d.ts +31 -1
  133. package/server.d.ts.map +1 -1
  134. package/server.js +53 -3
  135. package/server.js.map +1 -1
  136. package/src/config.ts +19 -0
  137. package/src/domains/agentexecutions/approve.ts +67 -0
  138. package/src/domains/agentexecutions/fetch.ts +112 -0
  139. package/src/domains/agentexecutions/run.ts +112 -0
  140. package/src/domains/agentexecutions/tools.ts +139 -0
  141. package/src/domains/apply.integration.test.ts +82 -6
  142. package/src/domains/datastores/apply.ts +33 -0
  143. package/src/domains/datastores/delete.ts +47 -0
  144. package/src/domains/datastores/fetch.ts +32 -0
  145. package/src/domains/datastores/resources.ts +21 -0
  146. package/src/domains/datastores/tools.ts +76 -0
  147. package/src/domains/deletes.integration.test.ts +49 -2
  148. package/src/domains/environments/apply.ts +40 -0
  149. package/src/domains/environments/delete.ts +45 -0
  150. package/src/domains/environments/fetch.ts +39 -0
  151. package/src/domains/environments/resources.ts +21 -0
  152. package/src/domains/environments/tools.ts +81 -0
  153. package/src/domains/executions/cancel.ts +148 -0
  154. package/src/domains/executions/tools.ts +45 -0
  155. package/src/domains/executions.integration.test.ts +376 -0
  156. package/src/domains/reads.integration.test.ts +51 -5
  157. package/src/domains/records/calls.ts +209 -0
  158. package/src/domains/records/errors.ts +98 -0
  159. package/src/domains/records/records.integration.test.ts +313 -0
  160. package/src/domains/records/tools.ts +210 -0
  161. package/src/domains/resources.integration.test.ts +38 -2
  162. package/src/domains/resourceuri.test.ts +11 -2
  163. package/src/domains/resourceuri.ts +2 -0
  164. package/src/domains/search/search.integration.test.ts +18 -2
  165. package/src/domains/search/tools.ts +12 -7
  166. package/src/domains/skills/tools.ts +34 -1
  167. package/src/domains/skills/versions.ts +47 -0
  168. package/src/domains/versions.integration.test.ts +212 -0
  169. package/src/domains/workflowexecutions/approvals.ts +102 -0
  170. package/src/domains/workflowexecutions/run.ts +87 -0
  171. package/src/domains/workflowexecutions/tools.ts +120 -6
  172. package/src/domains/workflows/tools.ts +90 -7
  173. package/src/domains/workflows/versions.ts +147 -0
  174. package/src/gen/agent.ts +28 -1
  175. package/src/gen/datastore.ts +264 -0
  176. package/src/gen/environment.ts +66 -0
  177. package/src/http.integration.test.ts +1 -0
  178. package/src/index.ts +12 -5
  179. package/src/server.ts +71 -5
@@ -0,0 +1,98 @@
1
+ // The records-domain error mapper (DD-005 SD-6) — a deliberate,
2
+ // documented divergence from the shared ../rpcerr.ts.
3
+ //
4
+ // Record-RPC domain errors carry agent-relayable messages that are
5
+ // cross-edition contract bytes (DD-002 SD-5): "that slot is already
6
+ // booked", "you are not allowed to insert records in bookings". The
7
+ // shared helper would rewrite them ("Check your API key permissions")
8
+ // and discards google.rpc.ErrorInfo. Here the domain codes pass the
9
+ // server's message through VERBATIM as isError JSON text
10
+ // `{error, code, reason, constraint}` — reason/constraint extracted
11
+ // from ErrorInfo — so the model can self-correct (retry another slot
12
+ // on CONSTRAINT_VIOLATION; stop and relay on PERMISSION_DENIED).
13
+ // Transport codes still delegate to the shared helper, whose advice is
14
+ // right for them.
15
+
16
+ import { Code, ConnectError } from "@connectrpc/connect";
17
+ import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
18
+ import { ErrorInfoSchema } from "@stigmer/protos/google/rpc/error_details_pb";
19
+ import { rpcError } from "../rpcerr.js";
20
+ import { errorResult, textResult } from "../toolresult.js";
21
+
22
+ /**
23
+ * The gRPC codes whose messages are the record-RPC domain contract
24
+ * (DD-005 SD-6): declared constraint messages, fixed denial texts, and
25
+ * domain validation — all written to be relayed to end users verbatim.
26
+ */
27
+ const DOMAIN_CODES: ReadonlySet<Code> = new Set([
28
+ Code.PermissionDenied,
29
+ Code.AlreadyExists,
30
+ Code.FailedPrecondition,
31
+ Code.InvalidArgument,
32
+ Code.NotFound,
33
+ ]);
34
+
35
+ /** The structured error payload record tools return for domain errors. */
36
+ export interface RecordToolError {
37
+ /** The server's relayable message, byte-for-byte. */
38
+ error: string;
39
+ /** gRPC status name in SCREAMING_SNAKE (e.g. ALREADY_EXISTS). */
40
+ code: string;
41
+ /** ErrorInfo reason (e.g. CONSTRAINT_VIOLATION), when present. */
42
+ reason?: string;
43
+ /** Violated constraint name from ErrorInfo metadata, when present. */
44
+ constraint?: string;
45
+ }
46
+
47
+ /**
48
+ * Run a record-tool body: a string payload becomes a text result; a
49
+ * domain error becomes an isError JSON result carrying the verbatim
50
+ * message + ErrorInfo companions; a transport error delegates to the
51
+ * shared classifier. The records analog of ../toolresult.ts
52
+ * textOrError, and the only try/catch in this domain.
53
+ */
54
+ export async function recordResult(
55
+ toolContext: string,
56
+ produce: () => Promise<string>,
57
+ ): Promise<CallToolResult> {
58
+ try {
59
+ return textResult(await produce());
60
+ } catch (err) {
61
+ const ce = ConnectError.from(err);
62
+ if (DOMAIN_CODES.has(ce.code)) {
63
+ return {
64
+ content: [{ type: "text", text: JSON.stringify(domainError(ce)) }],
65
+ isError: true,
66
+ };
67
+ }
68
+ return errorResult(rpcError(ce, toolContext));
69
+ }
70
+ }
71
+
72
+ /** Project a domain ConnectError into the structured tool payload. */
73
+ export function domainError(ce: ConnectError): RecordToolError {
74
+ const payload: RecordToolError = {
75
+ error: ce.rawMessage,
76
+ code: grpcStatusName(ce.code),
77
+ };
78
+ // The record RPCs attach one google.rpc.ErrorInfo per domain error
79
+ // (domain datastore.stigmer.ai); absence means an older server — the
80
+ // message alone still carries the contract.
81
+ const details = ce.findDetails(ErrorInfoSchema);
82
+ if (details.length > 0) {
83
+ const info = details[0];
84
+ if (info.reason !== "") {
85
+ payload.reason = info.reason;
86
+ }
87
+ const constraint = info.metadata["constraint"];
88
+ if (constraint !== undefined && constraint !== "") {
89
+ payload.constraint = constraint;
90
+ }
91
+ }
92
+ return payload;
93
+ }
94
+
95
+ /** Connect's PascalCase code name → the gRPC SCREAMING_SNAKE status name. */
96
+ function grpcStatusName(code: Code): string {
97
+ return Code[code].replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
98
+ }
@@ -0,0 +1,313 @@
1
+ // In-process integration test for the record tools (search-pattern:
2
+ // real Connect backend with stubbed record services, real MCP client
3
+ // over an in-memory transport).
4
+ //
5
+ // Verifies the T05 contract surface:
6
+ // - the records-only roster is exactly the five tools (T05 R1), with
7
+ // honest annotations surfaced through tools/list (pinning the SDK's
8
+ // annotations support) and NO org argument (agent audience);
9
+ // - the main roster carries the same five tools WITH the org argument
10
+ // (direct audience);
11
+ // - argument → request mapping (typed filter, "in" → is_in, paging);
12
+ // - the records-own error mapper: domain errors pass the server's
13
+ // message verbatim as {error, code, reason, constraint} JSON with
14
+ // ErrorInfo companions; transport errors delegate to the shared
15
+ // classifier (DD-005 SD-6).
16
+
17
+ import { create } from "@bufbuild/protobuf";
18
+ import { Code, ConnectError, type ConnectRouter } from "@connectrpc/connect";
19
+ import { connectNodeAdapter } from "@connectrpc/connect-node";
20
+ import {
21
+ createServer as createHttp2Server,
22
+ type Http2Server,
23
+ type ServerHttp2Session,
24
+ } from "node:http2";
25
+ import type { AddressInfo } from "node:net";
26
+
27
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
28
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
29
+ import { DatastoreRecordCommandController } from "@stigmer/protos/ai/stigmer/agentic/datastore/v1/record_command_pb";
30
+ import {
31
+ DatastoreDescriptionSchema,
32
+ RecordEnvelopeSchema,
33
+ RecordListSchema,
34
+ type FindRecordsRequest,
35
+ type InsertRecordRequest,
36
+ } from "@stigmer/protos/ai/stigmer/agentic/datastore/v1/record_io_pb";
37
+ import { DatastoreRecordQueryController } from "@stigmer/protos/ai/stigmer/agentic/datastore/v1/record_query_pb";
38
+ import { ErrorInfoSchema } from "@stigmer/protos/google/rpc/error_details_pb";
39
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
40
+
41
+ import { configureLogger } from "../../logger";
42
+ import { createRecordsServer, createServer } from "../../server";
43
+
44
+ configureLogger({ level: "error", format: "text" });
45
+
46
+ const RECORD_TOOLS = [
47
+ "describe_datastore",
48
+ "find_records",
49
+ "insert_record",
50
+ "update_record",
51
+ "delete_record",
52
+ ];
53
+
54
+ let backend: Http2Server;
55
+ let client: Client;
56
+ const openSessions = new Set<ServerHttp2Session>();
57
+
58
+ /** The next stubbed outcome per RPC; tests set these. */
59
+ let findResponse: () => ReturnType<typeof create<typeof RecordListSchema>>;
60
+ let insertOutcome: () => ReturnType<typeof create<typeof RecordEnvelopeSchema>>;
61
+
62
+ /**
63
+ * Requests the stubs captured. An object (not two `let`s) because TS
64
+ * does not reset let-narrowing across awaited calls for closure
65
+ * assignments — property narrowing it does.
66
+ */
67
+ const captured: {
68
+ find?: FindRecordsRequest;
69
+ insert?: InsertRecordRequest;
70
+ } = {};
71
+
72
+ interface ToolResult {
73
+ content: Array<{ type: string; text?: string }>;
74
+ isError?: boolean;
75
+ }
76
+
77
+ async function callTool(name: string, args: Record<string, unknown>): Promise<ToolResult> {
78
+ return (await client.callTool({ name, arguments: args })) as ToolResult;
79
+ }
80
+
81
+ beforeAll(async () => {
82
+ const routes = (router: ConnectRouter) => {
83
+ router.service(DatastoreRecordQueryController, {
84
+ findRecords: (req) => {
85
+ captured.find = req;
86
+ return findResponse();
87
+ },
88
+ describeDatastore: () =>
89
+ create(DatastoreDescriptionSchema, {
90
+ datastore: "clinic",
91
+ timezone: "Asia/Kolkata",
92
+ partitions: ["default"],
93
+ }),
94
+ });
95
+ router.service(DatastoreRecordCommandController, {
96
+ insertRecord: (req) => {
97
+ captured.insert = req;
98
+ return insertOutcome();
99
+ },
100
+ updateRecord: () => create(RecordEnvelopeSchema, { id: "dsr_updated" }),
101
+ deleteRecord: () => create(RecordEnvelopeSchema, { id: "dsr_deleted" }),
102
+ });
103
+ };
104
+ backend = createHttp2Server(connectNodeAdapter({ routes }));
105
+ backend.on("session", (session) => {
106
+ openSessions.add(session);
107
+ session.on("close", () => openSessions.delete(session));
108
+ });
109
+ await new Promise<void>((resolve) => backend.listen(0, "127.0.0.1", resolve));
110
+ const port = (backend.address() as AddressInfo).port;
111
+
112
+ // The records-only roster is the surface under test — the audience
113
+ // the runner-synthesized attachment serves.
114
+ const mcp = createRecordsServer({ serverAddress: `127.0.0.1:${port}`, apiKey: "" });
115
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
116
+ client = new Client({ name: "records-integration", version: "test" });
117
+ await Promise.all([mcp.connect(serverTransport), client.connect(clientTransport)]);
118
+ });
119
+
120
+ afterAll(async () => {
121
+ await client?.close();
122
+ for (const session of openSessions) session.destroy();
123
+ await new Promise<void>((resolve) => backend.close(() => resolve()));
124
+ });
125
+
126
+ describe("records roster (T05 R1)", () => {
127
+ it("exposes exactly the five record tools with honest annotations and no org argument", async () => {
128
+ const { tools } = await client.listTools();
129
+ expect(tools.map((t) => t.name).sort()).toEqual([...RECORD_TOOLS].sort());
130
+
131
+ const byName = new Map(tools.map((t) => [t.name, t]));
132
+ // Annotations are part of the DD-005 contract for external clients
133
+ // and the classifier; this pins the SDK actually surfacing them.
134
+ expect(byName.get("find_records")?.annotations).toMatchObject({ readOnlyHint: true });
135
+ expect(byName.get("describe_datastore")?.annotations).toMatchObject({ readOnlyHint: true });
136
+ expect(byName.get("update_record")?.annotations).toMatchObject({ idempotentHint: true });
137
+ expect(byName.get("delete_record")?.annotations).toMatchObject({
138
+ destructiveHint: true,
139
+ idempotentHint: true,
140
+ });
141
+
142
+ // The agent audience gets no org argument — a session-bound
143
+ // caller's org is server-derived, and offering the argument would
144
+ // only invite INVALID_ARGUMENT rejections (T05 R3).
145
+ for (const tool of tools) {
146
+ const properties = (tool.inputSchema as { properties?: Record<string, unknown> }).properties;
147
+ expect(Object.keys(properties ?? {}), tool.name).not.toContain("org");
148
+ }
149
+ });
150
+
151
+ it("the main roster carries the five tools WITH the org argument", async () => {
152
+ // Direct principals (external MCP clients) must be able to name the
153
+ // org their credential does not carry (DD-006 session-14 amendment).
154
+ const full = createServer({ serverAddress: "127.0.0.1:1", apiKey: "" });
155
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
156
+ const fullClient = new Client({ name: "records-full-roster", version: "test" });
157
+ await Promise.all([full.connect(serverTransport), fullClient.connect(clientTransport)]);
158
+ try {
159
+ const { tools } = await fullClient.listTools();
160
+ const names = tools.map((t) => t.name);
161
+ for (const name of RECORD_TOOLS) {
162
+ expect(names).toContain(name);
163
+ }
164
+ const find = tools.find((t) => t.name === "find_records");
165
+ const properties = (find?.inputSchema as { properties?: Record<string, unknown> })
166
+ .properties;
167
+ expect(Object.keys(properties ?? {})).toContain("org");
168
+ } finally {
169
+ await fullClient.close();
170
+ }
171
+ });
172
+ });
173
+
174
+ describe("argument → request mapping", () => {
175
+ it("builds the typed filter (in → is_in), order_by, and paging", async () => {
176
+ findResponse = () =>
177
+ create(RecordListSchema, {
178
+ records: [create(RecordEnvelopeSchema, { id: "dsr_1" })],
179
+ total: 1,
180
+ limit: 25,
181
+ });
182
+ captured.find = undefined;
183
+
184
+ const result = await callTool("find_records", {
185
+ datastore: "clinic",
186
+ collection: "bookings",
187
+ conditions: [
188
+ { field: "status", op: "eq", value: "confirmed" },
189
+ { field: "patient_name", op: "in", values: ["Asha", "Ravi"] },
190
+ ],
191
+ order_by: { field: "slot_start", direction: "desc" },
192
+ limit: 10,
193
+ offset: 20,
194
+ });
195
+
196
+ expect(result.isError).toBeFalsy();
197
+ // Assertion, not annotation: control-flow analysis otherwise pins the
198
+ // const to the `= undefined` reset above (the stub assigns in a
199
+ // closure the analysis cannot see across the await).
200
+ const req = captured.find as FindRecordsRequest | undefined;
201
+ expect(req?.datastore).toBe("clinic");
202
+ expect(req?.org).toBe(""); // agent audience: org never travels
203
+ expect(req?.partition).toBe(""); // partition is never a tool argument (DD-010)
204
+ expect(req?.filter?.conditions).toHaveLength(2);
205
+ expect(req?.filter?.conditions[0]).toMatchObject({ field: "status", op: 1 /* eq */ });
206
+ expect(req?.filter?.conditions[1]).toMatchObject({ field: "patient_name", op: 7 /* is_in */ });
207
+ expect(req?.filter?.conditions[1]?.values).toHaveLength(2);
208
+ expect(req?.orderBy).toMatchObject({ field: "slot_start", direction: 2 /* desc */ });
209
+ expect(req?.limit).toBe(10);
210
+ expect(req?.offset).toBe(20);
211
+
212
+ const body = JSON.parse(result.content[0]?.text ?? "{}") as { total?: number };
213
+ expect(body.total).toBe(1);
214
+ });
215
+
216
+ it("passes the record payload through as a Struct, untouched", async () => {
217
+ insertOutcome = () => create(RecordEnvelopeSchema, { id: "dsr_new" });
218
+ captured.insert = undefined;
219
+
220
+ const result = await callTool("insert_record", {
221
+ datastore: "clinic",
222
+ collection: "bookings",
223
+ record: { slot_start: "2026-07-21T04:30:00Z", patient_name: "Asha" },
224
+ });
225
+
226
+ expect(result.isError).toBeFalsy();
227
+ const req = captured.insert as InsertRecordRequest | undefined;
228
+ expect(req?.record).toMatchObject({
229
+ slot_start: "2026-07-21T04:30:00Z",
230
+ patient_name: "Asha",
231
+ });
232
+ });
233
+ });
234
+
235
+ describe("records error mapper (DD-005 SD-6)", () => {
236
+ it("passes a constraint violation through verbatim with ErrorInfo companions", async () => {
237
+ insertOutcome = () => {
238
+ throw new ConnectError("that slot is already booked", Code.AlreadyExists, undefined, [
239
+ {
240
+ desc: ErrorInfoSchema,
241
+ value: create(ErrorInfoSchema, {
242
+ reason: "CONSTRAINT_VIOLATION",
243
+ domain: "datastore.stigmer.ai",
244
+ metadata: { constraint: "one_confirmed_per_slot" },
245
+ }),
246
+ },
247
+ ]);
248
+ };
249
+
250
+ const result = await callTool("insert_record", {
251
+ datastore: "clinic",
252
+ collection: "bookings",
253
+ record: { slot_start: "2026-07-21T04:30:00Z", patient_name: "Ravi" },
254
+ });
255
+
256
+ expect(result.isError).toBe(true);
257
+ expect(JSON.parse(result.content[0]?.text ?? "{}")).toEqual({
258
+ error: "that slot is already booked",
259
+ code: "ALREADY_EXISTS",
260
+ reason: "CONSTRAINT_VIOLATION",
261
+ constraint: "one_confirmed_per_slot",
262
+ });
263
+ });
264
+
265
+ it("passes a permission denial through verbatim — never the shared rewrite", async () => {
266
+ insertOutcome = () => {
267
+ throw new ConnectError(
268
+ "you are not allowed to insert records in schedule_exceptions",
269
+ Code.PermissionDenied,
270
+ undefined,
271
+ [
272
+ {
273
+ desc: ErrorInfoSchema,
274
+ value: create(ErrorInfoSchema, {
275
+ reason: "VERB_DENIED",
276
+ domain: "datastore.stigmer.ai",
277
+ }),
278
+ },
279
+ ],
280
+ );
281
+ };
282
+
283
+ const result = await callTool("insert_record", {
284
+ datastore: "clinic",
285
+ collection: "schedule_exceptions",
286
+ record: { exception_date: "2026-07-22" },
287
+ });
288
+
289
+ expect(result.isError).toBe(true);
290
+ const body = JSON.parse(result.content[0]?.text ?? "{}") as Record<string, string>;
291
+ // The relayable domain bytes — NOT "Check your API key permissions".
292
+ expect(body.error).toBe("you are not allowed to insert records in schedule_exceptions");
293
+ expect(body.code).toBe("PERMISSION_DENIED");
294
+ expect(body.reason).toBe("VERB_DENIED");
295
+ expect(body.constraint).toBeUndefined();
296
+ });
297
+
298
+ it("delegates transport codes to the shared classifier", async () => {
299
+ findResponse = () => {
300
+ throw new ConnectError("upstream down", Code.Unavailable);
301
+ };
302
+
303
+ const result = await callTool("find_records", {
304
+ datastore: "clinic",
305
+ collection: "bookings",
306
+ });
307
+
308
+ expect(result.isError).toBe(true);
309
+ expect(result.content[0]?.text).toBe(
310
+ "Stigmer server is unavailable. Ensure it is running and reachable.",
311
+ );
312
+ });
313
+ });
@@ -0,0 +1,210 @@
1
+ // MCP tools for the Datastore record domain — the five agent-facing
2
+ // record tools of DD-005: 1:1 projections of the record RPCs, with the
3
+ // records-own error mapper (errors.ts) and honest MCP annotations (the
4
+ // bridge's first use of annotations; the platform's own connect-time
5
+ // classifier honors destructiveHint fail-closed for external clients,
6
+ // while the runner-synthesized attachment is approval-free by
7
+ // construction and never passes through that classifier).
8
+ //
9
+ // Two audiences, one definition (registered per roster):
10
+ // - "agent" (the records-only roster the runner-synthesized
11
+ // attachment connects to): NO `org` argument — a session-bound
12
+ // caller's org is server-derived from the session, and an explicit
13
+ // org is rejected (T05 R3), so offering the argument would only
14
+ // invite rejected calls.
15
+ // - "direct" (the main roster external MCP clients see): optional
16
+ // `org`, which cloud direct principals must name (their credential
17
+ // carries no ambient org — the DD-006 session-14 amendment). OSS
18
+ // resolves an empty org to the local system org.
19
+ // `partition` is deliberately NOT a tool argument for either audience
20
+ // (DD-010: never from tool arguments); partition-explicit work is the
21
+ // console/CLI/SDK surface.
22
+
23
+ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
24
+ import { z } from "zod";
25
+
26
+ import { resolveToken, type BackendTarget } from "../client.js";
27
+ import {
28
+ deleteRecord,
29
+ describeDatastore,
30
+ findRecords,
31
+ insertRecord,
32
+ updateRecord,
33
+ type ConditionArg,
34
+ } from "./calls.js";
35
+ import { recordResult } from "./errors.js";
36
+
37
+ /** Which roster the tools are being registered on (see file header). */
38
+ export type RecordToolAudience = "agent" | "direct";
39
+
40
+ const ENCODINGS =
41
+ "Field value encodings: date YYYY-MM-DD, time HH:MM[:SS], timestamp RFC 3339 UTC " +
42
+ "(e.g. 2026-07-21T04:30:00Z).";
43
+
44
+ const scalar = z.union([z.string(), z.number(), z.boolean()]);
45
+
46
+ const conditionShape = z.object({
47
+ field: z
48
+ .string()
49
+ .describe("Declared field name, or a filterable system field (id, created_at, updated_at)."),
50
+ op: z
51
+ .enum(["eq", "neq", "gt", "gte", "lt", "lte", "in", "not_in", "is_null", "not_null"])
52
+ .describe(
53
+ "Comparison operator. eq/neq/in/not_in for string and enum fields; " +
54
+ "gt/gte/lt/lte for numeric and temporal fields; is_null/not_null for optional fields.",
55
+ ),
56
+ value: scalar
57
+ .nullable()
58
+ .optional()
59
+ .describe("Comparison value for scalar operators, in the field's canonical encoding."),
60
+ values: z.array(scalar).optional().describe("Comparison values for in / not_in."),
61
+ });
62
+
63
+ /** Register the five record tools for one audience; returns the tool names. */
64
+ export function registerRecordTools(
65
+ server: McpServer,
66
+ target: BackendTarget,
67
+ audience: RecordToolAudience,
68
+ ): string[] {
69
+ // The org argument exists only on the direct roster (file header).
70
+ const orgShape: { org?: z.ZodOptional<z.ZodString> } = {};
71
+ if (audience === "direct") {
72
+ orgShape.org = z
73
+ .string()
74
+ .optional()
75
+ .describe(
76
+ "Organization that owns the datastore. Required on Stigmer Cloud; " +
77
+ "omit against a local backend.",
78
+ );
79
+ }
80
+
81
+ server.registerTool(
82
+ "describe_datastore",
83
+ {
84
+ description:
85
+ "Describe a datastore: its collections, field declarations and encodings, constraint " +
86
+ "messages, data partitions, and the verbs you are allowed to use per collection " +
87
+ "(empty access means you are not allowed to touch that collection). A read verb may " +
88
+ "carry readable_fields: reads then return only those fields, and only they may appear " +
89
+ "in filter conditions and order_by (empty readable_fields means every field). Call " +
90
+ `this before the first record operation against an unfamiliar datastore. ${ENCODINGS}`,
91
+ inputSchema: {
92
+ datastore: z.string().describe("Datastore slug (e.g. clinic)."),
93
+ ...orgShape,
94
+ },
95
+ annotations: { readOnlyHint: true },
96
+ },
97
+ (args, extra) =>
98
+ recordResult(`datastore "${args.datastore}"`, () =>
99
+ describeDatastore(target.serverAddress, resolveToken(extra, target.apiKey), args),
100
+ ),
101
+ );
102
+
103
+ server.registerTool(
104
+ "find_records",
105
+ {
106
+ description:
107
+ "Find records in a datastore collection with a typed filter (conditions are AND-combined). " +
108
+ "Returns records plus total/limit/offset for paging. Results are ordered by created_at " +
109
+ "descending unless order_by is given. Records carry only the fields your grant allows " +
110
+ "(describe_datastore lists them as readable_fields); conditions and order_by on other " +
111
+ `fields are rejected. ${ENCODINGS}`,
112
+ inputSchema: {
113
+ datastore: z.string().describe("Datastore slug (e.g. clinic)."),
114
+ ...orgShape,
115
+ collection: z.string().describe("Collection to query (e.g. bookings)."),
116
+ conditions: z
117
+ .array(conditionShape)
118
+ .optional()
119
+ .describe("Filter conditions, AND-combined. Omit to list all readable records."),
120
+ order_by: z
121
+ .object({
122
+ field: z.string().describe("Field to sort by."),
123
+ direction: z.enum(["asc", "desc"]).optional().describe("Sort direction (default asc)."),
124
+ })
125
+ .optional()
126
+ .describe("Sort order. Omit for created_at descending with id tiebreak."),
127
+ limit: z.number().int().optional().describe("Page size (default 25, max 100)."),
128
+ offset: z.number().int().optional().describe("Records to skip for paging."),
129
+ },
130
+ annotations: { readOnlyHint: true },
131
+ },
132
+ (args, extra) =>
133
+ recordResult(`records in "${args.datastore}/${args.collection}"`, () =>
134
+ findRecords(target.serverAddress, resolveToken(extra, target.apiKey), {
135
+ ...args,
136
+ conditions: args.conditions as ConditionArg[] | undefined,
137
+ }),
138
+ ),
139
+ );
140
+
141
+ server.registerTool(
142
+ "insert_record",
143
+ {
144
+ description:
145
+ "Insert one record into a datastore collection. System fields (id, created_at, " +
146
+ "updated_at, created_by) are server-stamped — never include them. Declared constraints " +
147
+ "are enforced by the store; a violation returns the constraint's message verbatim " +
148
+ "(e.g. a taken slot returns ALREADY_EXISTS — pick another, do not retry the same one). " +
149
+ `When uncertain whether a record already exists, find first. ${ENCODINGS}`,
150
+ inputSchema: {
151
+ datastore: z.string().describe("Datastore slug (e.g. clinic)."),
152
+ ...orgShape,
153
+ collection: z.string().describe("Collection to insert into (e.g. bookings)."),
154
+ record: z
155
+ .record(z.unknown())
156
+ .describe("Declared fields for the new record, in canonical encodings."),
157
+ },
158
+ },
159
+ (args, extra) =>
160
+ recordResult(`record in "${args.datastore}/${args.collection}"`, () =>
161
+ insertRecord(target.serverAddress, resolveToken(extra, target.apiKey), args),
162
+ ),
163
+ );
164
+
165
+ server.registerTool(
166
+ "update_record",
167
+ {
168
+ description:
169
+ "Update one record by id with a partial merge: only the supplied fields change, and an " +
170
+ "explicit null clears a field. Constraints are re-evaluated on the merged result. " +
171
+ `Returns the full updated record. ${ENCODINGS}`,
172
+ inputSchema: {
173
+ datastore: z.string().describe("Datastore slug (e.g. clinic)."),
174
+ ...orgShape,
175
+ collection: z.string().describe("Collection holding the record."),
176
+ id: z.string().describe("Record id (from a previous find or insert)."),
177
+ fields: z
178
+ .record(z.unknown())
179
+ .describe("Fields to merge. Explicit null clears a field; omitted fields keep their values."),
180
+ },
181
+ annotations: { idempotentHint: true },
182
+ },
183
+ (args, extra) =>
184
+ recordResult(`record "${args.id}" in "${args.datastore}/${args.collection}"`, () =>
185
+ updateRecord(target.serverAddress, resolveToken(extra, target.apiKey), args),
186
+ ),
187
+ );
188
+
189
+ server.registerTool(
190
+ "delete_record",
191
+ {
192
+ description:
193
+ "Delete one record by id. Returns the deleted record. Record tools never delete " +
194
+ "collections or datastores.",
195
+ inputSchema: {
196
+ datastore: z.string().describe("Datastore slug (e.g. clinic)."),
197
+ ...orgShape,
198
+ collection: z.string().describe("Collection holding the record."),
199
+ id: z.string().describe("Record id (from a previous find or insert)."),
200
+ },
201
+ annotations: { destructiveHint: true, idempotentHint: true },
202
+ },
203
+ (args, extra) =>
204
+ recordResult(`record "${args.id}" in "${args.datastore}/${args.collection}"`, () =>
205
+ deleteRecord(target.serverAddress, resolveToken(extra, target.apiKey), args),
206
+ ),
207
+ );
208
+
209
+ return ["describe_datastore", "find_records", "insert_record", "update_record", "delete_record"];
210
+ }