@unbrained/pm-cli 2026.8.25 → 2026.8.27

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 (206) hide show
  1. package/.agents/skills/HARNESS_COMPATIBILITY.md +32 -0
  2. package/.agents/skills/README.md +47 -0
  3. package/.agents/skills/pm-developer/SKILL.md +117 -0
  4. package/.agents/skills/pm-developer/references/COMMAND_PLAYBOOK.md +49 -0
  5. package/.agents/skills/pm-developer/references/GRAPH_AND_RELATIONSHIPS.md +91 -0
  6. package/.agents/skills/pm-developer/references/MULTI_AGENT_MERGE.md +72 -0
  7. package/.agents/skills/pm-developer/references/PROMPTS.md +17 -0
  8. package/.agents/skills/pm-developer/references/SCRIPTING_COMPOSITION.md +82 -0
  9. package/.agents/skills/pm-developer/references/TOKEN_BUDGETS.md +85 -0
  10. package/.agents/skills/pm-extensions/SKILL.md +106 -0
  11. package/.agents/skills/pm-extensions/references/AUTHORING.md +95 -0
  12. package/.agents/skills/pm-extensions/references/LIFECYCLE.md +40 -0
  13. package/.agents/skills/pm-extensions/references/TROUBLESHOOTING.md +25 -0
  14. package/.agents/skills/pm-sdk/SKILL.md +107 -0
  15. package/.agents/skills/pm-sdk/references/DOMAIN_MODELING.md +78 -0
  16. package/.agents/skills/pm-sdk/references/INTEGRATION_CHECKLIST.md +31 -0
  17. package/.agents/skills/pm-sdk/references/PROMPTS.md +13 -0
  18. package/.agents/skills/pm-sdk/references/SURFACE_MAP.md +82 -0
  19. package/.agents/skills/pm-user/SKILL.md +111 -0
  20. package/.agents/skills/pm-user/references/BACKLOG_SHAPING.md +105 -0
  21. package/.agents/skills/pm-user/references/PROMPTS.md +17 -0
  22. package/.agents/skills/pm-user/references/WORKFLOWS.md +35 -0
  23. package/.claude-plugin/marketplace.json +2 -2
  24. package/CHANGELOG.md +58 -3
  25. package/README.md +8 -5
  26. package/dist/cli/commander-usage.js +11 -7
  27. package/dist/cli/error-guidance.js +3 -3
  28. package/dist/cli/help-content.d.ts +2 -0
  29. package/dist/cli/help-content.js +53 -17
  30. package/dist/cli/help-json-payload.d.ts +8 -2
  31. package/dist/cli/help-json-payload.js +46 -12
  32. package/dist/cli/main.js +52 -74
  33. package/dist/cli/register-annotations.js +27 -21
  34. package/dist/cli/register-setup.js +98 -57
  35. package/dist/cli-bundle/bundle-manifest.json +156 -156
  36. package/dist/cli-bundle/chunks/chunk-3OO3W6FW.js +202 -0
  37. package/dist/cli-bundle/chunks/chunk-52EKTW6V.js +3 -0
  38. package/dist/cli-bundle/chunks/{chunk-QLUORNIB.js → chunk-CVBBGWW5.js} +62 -44
  39. package/dist/cli-bundle/chunks/chunk-MFNTKMTI.js +13 -0
  40. package/dist/cli-bundle/chunks/chunk-OS27HHBN.js +35 -0
  41. package/dist/cli-bundle/chunks/chunk-QTO7USTH.js +2 -0
  42. package/dist/cli-bundle/chunks/{chunk-5I5RWIJC.js → chunk-R4ETAOJC.js} +2 -2
  43. package/dist/cli-bundle/chunks/{chunk-OWHNAR2B.js → chunk-SH6P7FXI.js} +2 -2
  44. package/dist/cli-bundle/chunks/chunk-SHMDY36D.js +8 -0
  45. package/dist/cli-bundle/chunks/{chunk-244MI4GS.js → chunk-SKXLJIEK.js} +60 -60
  46. package/dist/cli-bundle/chunks/chunk-TNX6HC54.js +3 -0
  47. package/dist/cli-bundle/chunks/{register-list-query-XVN2ZLI7.js → register-list-query-EUWM6VII.js} +2 -2
  48. package/dist/cli-bundle/chunks/{register-mutation-QCKAEGIJ.js → register-mutation-FD4HSAVU.js} +4 -4
  49. package/dist/cli-bundle/chunks/{register-operations-SDEAXE7E.js → register-operations-HRMNFEC3.js} +2 -2
  50. package/dist/cli-bundle/chunks/register-setup-33GNICLX.js +2 -0
  51. package/dist/cli-bundle/focused-chunks/{chunk-IBZZZGK3.js → chunk-2AGZ5BRT.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/chunk-4BR5UU52.js +50 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-OHIHZ7HS.js → chunk-6GCRSLPG.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-OVJL6NZE.js → chunk-AD6ULRAF.js} +4 -4
  55. package/dist/cli-bundle/focused-chunks/{chunk-7YCDTCBC.js → chunk-AQ5IYEZZ.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-YO3ZF3FI.js → chunk-EKX37ZHA.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-N7W67YIG.js → chunk-FC2AXLB5.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-H5JZEIQV.js → chunk-HC7ODMH3.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{chunk-NOOZGIXP.js → chunk-HVQ22RC4.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-A644DUFQ.js → chunk-MEASX544.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-RAFKLNZX.js → chunk-MXTYGECH.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{chunk-2UIWOP3O.js → chunk-SUBSWYW3.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{chunk-VXWATRFL.js → chunk-XDPYBQCF.js} +9 -9
  64. package/dist/cli-bundle/focused-chunks/{chunk-XUQPEKRN.js → chunk-Y3JJXRVK.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-GQR3WH3F.js → chunk-Y5A7SJJ7.js} +2 -2
  66. package/dist/cli-bundle/focused-chunks/chunk-YHWHX6YY.js +2 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-ONYQCALA.js → chunk-YVVZ3LQ6.js} +6 -6
  68. package/dist/cli-bundle/focused-chunks/chunk-Z2USIBR2.js +5 -0
  69. package/dist/cli-bundle/main.js +15 -14
  70. package/dist/cli-bundle/sdk-authoring.js +1 -1
  71. package/dist/cli-bundle/sdk-contracts.js +2 -2
  72. package/dist/cli-bundle/sdk-core.js +31 -31
  73. package/dist/cli-bundle/sdk-governance.js +1 -1
  74. package/dist/cli-bundle/sdk-graph.js +1 -1
  75. package/dist/cli-bundle/sdk-merge.js +31 -31
  76. package/dist/cli-bundle/sdk-query.js +1 -1
  77. package/dist/cli-bundle/sdk-runtime.js +1 -1
  78. package/dist/cli-bundle/sdk-testing.js +1 -1
  79. package/dist/cli-bundle/sdk.js +32 -6
  80. package/dist/core/extensions/manifest-schema.d.ts +20 -0
  81. package/dist/core/extensions/manifest-schema.js +28 -10
  82. package/dist/core/governance/issue-codes.d.ts +11 -2
  83. package/dist/core/governance/issue-codes.js +29 -10
  84. package/dist/core/item/item-format.js +3 -3
  85. package/dist/core/store/item-store.js +12 -5
  86. package/dist/mcp/http-server.d.ts +60 -0
  87. package/dist/mcp/http-server.js +451 -0
  88. package/dist/mcp/legacy-adapter.d.ts +50 -0
  89. package/dist/mcp/legacy-adapter.js +64 -0
  90. package/dist/mcp/server.d.ts +42 -9
  91. package/dist/mcp/server.js +572 -59
  92. package/dist/mcp/tool-definitions.d.ts +2 -0
  93. package/dist/mcp/tool-definitions.js +2 -2
  94. package/dist/sdk/agent/closed-domain-contracts.d.ts +1 -1
  95. package/dist/sdk/agent/closed-domain-contracts.js +24 -2
  96. package/dist/sdk/agent/refusal-closure-census.d.ts +6 -2
  97. package/dist/sdk/agent/refusal-closure-census.js +16 -8
  98. package/dist/sdk/agent-capability-contracts.js +6 -2
  99. package/dist/sdk/cli-bootstrap.js +3 -2
  100. package/dist/sdk/cli-contracts/command-aliases.js +15 -2
  101. package/dist/sdk/cli-contracts/enum-contracts.d.ts +4 -1
  102. package/dist/sdk/cli-contracts/enum-contracts.js +7 -2
  103. package/dist/sdk/cli-contracts/flag-contracts.js +9 -5
  104. package/dist/sdk/cli-contracts/grammar-contracts.d.ts +3 -3
  105. package/dist/sdk/cli-contracts/grammar-contracts.js +24 -17
  106. package/dist/sdk/cli-contracts/runtime-contracts.js +13 -11
  107. package/dist/sdk/cli-contracts/tool-schema.js +18 -15
  108. package/dist/sdk/cli-contracts.d.ts +1 -1
  109. package/dist/sdk/cli-contracts.js +3 -3
  110. package/dist/sdk/cli-program.js +3 -2
  111. package/dist/sdk/completion.js +40 -13
  112. package/dist/sdk/compose.d.ts +4 -1
  113. package/dist/sdk/compose.js +23 -36
  114. package/dist/sdk/extension/author-manifest.d.ts +22 -0
  115. package/dist/sdk/extension/author-manifest.js +93 -0
  116. package/dist/sdk/extension.js +6 -3
  117. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +20 -5
  118. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +18 -3
  119. package/dist/sdk/governance/health.js +7 -2
  120. package/dist/sdk/governance/upgrade.d.ts +2 -0
  121. package/dist/sdk/governance/upgrade.js +30 -8
  122. package/dist/sdk/governance/validate.js +8 -6
  123. package/dist/sdk/guide-topics.js +6 -6
  124. package/dist/sdk/index.d.ts +10 -2
  125. package/dist/sdk/index.js +11 -3
  126. package/dist/sdk/mcp/apps.d.ts +70 -0
  127. package/dist/sdk/mcp/apps.js +154 -0
  128. package/dist/sdk/mcp/authorization.d.ts +134 -0
  129. package/dist/sdk/mcp/authorization.js +405 -0
  130. package/dist/sdk/mcp/interactions.d.ts +118 -0
  131. package/dist/sdk/mcp/interactions.js +337 -0
  132. package/dist/sdk/mcp/protocol.d.ts +142 -0
  133. package/dist/sdk/mcp/protocol.js +174 -0
  134. package/dist/sdk/mcp/skills.d.ts +127 -0
  135. package/dist/sdk/mcp/skills.js +390 -0
  136. package/dist/sdk/mcp/subscriptions.d.ts +65 -0
  137. package/dist/sdk/mcp/subscriptions.js +212 -0
  138. package/dist/sdk/mcp/tasks.d.ts +107 -0
  139. package/dist/sdk/mcp/tasks.js +431 -0
  140. package/dist/sdk/mcp/transport.d.ts +30 -0
  141. package/dist/sdk/mcp/transport.js +261 -0
  142. package/dist/sdk/merge/receipts.d.ts +16 -0
  143. package/dist/sdk/merge/receipts.js +9 -8
  144. package/dist/sdk/read-output-contracts.js +16 -3
  145. package/dist/sdk/runtime-action-aliases.js +7 -3
  146. package/dist/sdk/runtime-input.js +12 -4
  147. package/dist/sdk/runtime-primitives.d.ts +2 -2
  148. package/dist/sdk/runtime-primitives.js +4 -4
  149. package/dist/sdk/test/execution.d.ts +6 -0
  150. package/dist/sdk/test/execution.js +32 -3
  151. package/docs/AGENT_PROVENANCE_ADR.md +6 -4
  152. package/docs/AGENT_RUNTIME_PRIMITIVES.md +6 -5
  153. package/docs/CLAUDE_CODE_PLUGIN.md +12 -5
  154. package/docs/CLI_GRAMMAR.md +7 -1
  155. package/docs/COMMANDS.md +2 -2
  156. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +8 -0
  157. package/docs/EXTENSIONS.md +36 -36
  158. package/docs/MCP_2026_07_28.md +160 -0
  159. package/docs/MCP_2026_07_28_CONFORMANCE.md +30 -0
  160. package/docs/MCP_REMOTE_TRANSPORT_SECURITY.md +180 -0
  161. package/docs/MCP_SKILLS_AND_APPS.md +107 -0
  162. package/docs/QUICKSTART.md +15 -15
  163. package/docs/README.md +5 -0
  164. package/docs/RELEASING.md +12 -3
  165. package/docs/SDK.md +22 -1
  166. package/docs/SDK_AGENT_SESSION_CONTEXT.md +18 -13
  167. package/docs/SDK_CONTEXT_INTEGRITY.md +6 -0
  168. package/docs/SDK_EVIDENCE_TRACEABILITY.md +9 -1
  169. package/docs/SDK_MCP_INTERACTIONS.md +227 -0
  170. package/docs/TESTING.md +4 -0
  171. package/docs/generated/AGENT_CAPABILITY_ROUTING.md +1 -1
  172. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +13 -11
  173. package/marketplace.json +2 -2
  174. package/package.json +15 -11
  175. package/packages/pm-beads/README.md +12 -6
  176. package/packages/pm-beads/docs/MIGRATION.md +53 -0
  177. package/packages/pm-beads/extensions/beads/index.ts +8 -0
  178. package/packages/pm-beads/extensions/beads/runtime.ts +671 -112
  179. package/packages/pm-beads/package.json +1 -1
  180. package/packages/pm-calendar/package.json +1 -1
  181. package/packages/pm-command-kit/package.json +1 -1
  182. package/packages/pm-digital-twin/package.json +1 -1
  183. package/packages/pm-governance-audit/package.json +1 -1
  184. package/packages/pm-guide-shell/package.json +1 -1
  185. package/packages/pm-kanban/package.json +1 -1
  186. package/packages/pm-lifecycle-hooks/package.json +1 -1
  187. package/packages/pm-linked-test-adapters/package.json +1 -1
  188. package/packages/pm-search-advanced/package.json +1 -1
  189. package/packages/pm-templates/package.json +1 -1
  190. package/packages/pm-todos/package.json +1 -1
  191. package/packages/pm-vcs/package.json +1 -1
  192. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  193. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  194. package/scripts/finalize-build.mjs +1 -0
  195. package/sdk/public-surface.json +902 -54
  196. package/dist/cli-bundle/chunks/chunk-2F3LUFMW.js +0 -8
  197. package/dist/cli-bundle/chunks/chunk-65MHLHAA.js +0 -2
  198. package/dist/cli-bundle/chunks/chunk-6C7GIMIL.js +0 -13
  199. package/dist/cli-bundle/chunks/chunk-QKGMHGEI.js +0 -202
  200. package/dist/cli-bundle/chunks/chunk-T2ENPRXF.js +0 -3
  201. package/dist/cli-bundle/chunks/chunk-TPQIBSL2.js +0 -3
  202. package/dist/cli-bundle/chunks/chunk-YQMYF3YD.js +0 -35
  203. package/dist/cli-bundle/chunks/register-setup-LXVBRCJ3.js +0 -2
  204. package/dist/cli-bundle/focused-chunks/chunk-42S3GGZ7.js +0 -50
  205. package/dist/cli-bundle/focused-chunks/chunk-7I23XGWO.js +0 -2
  206. package/dist/cli-bundle/focused-chunks/chunk-LMKG3DFE.js +0 -5
@@ -0,0 +1,337 @@
1
+ /**
2
+ * @module sdk/mcp/interactions
3
+ *
4
+ * Implements bounded MCP 2026-07-28 multi round-trip request, cache, and JSON
5
+ * Schema contracts without coupling protocol policy to a transport adapter.
6
+ */
7
+
8
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="469f704b-12eb-524d-bcc8-fb8f9f1775f2")}catch(e){}}();
9
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
10
+ import { PM_MCP_ERROR_CODES, PM_MCP_META_KEYS, PmMcpProtocolError, isMcpRecord, } from "./protocol.js";
11
+ /** Methods permitted inside a 2026-07-28 MRTR input request map. */
12
+ export const PM_MCP_INPUT_REQUEST_METHODS = [
13
+ "elicitation/create",
14
+ "roots/list",
15
+ "sampling/createMessage",
16
+ ];
17
+ /**
18
+ * Transport-neutral control signal used by SDK handlers to request an MRTR
19
+ * response without constructing or serializing JSON-RPC in domain code.
20
+ */
21
+ export class PmMcpInputRequiredError extends Error {
22
+ /** Server-authored input requests validated by the adapter. */
23
+ inputRequests;
24
+ /** Optional opaque continuation state echoed on retry. */
25
+ requestState;
26
+ /** Create an input-required control signal. */
27
+ constructor(input) {
28
+ super("MCP operation requires additional input");
29
+ this.name = "PmMcpInputRequiredError";
30
+ this.inputRequests = input.inputRequests;
31
+ this.requestState = input.requestState;
32
+ }
33
+ }
34
+ const INPUT_KEY_PATTERN = /^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/u;
35
+ const MAX_INPUT_REQUESTS = 32;
36
+ const MAX_INPUT_PAYLOAD_BYTES = 64 * 1024;
37
+ const MAX_REQUEST_STATE_BYTES = 16 * 1024;
38
+ const DEFAULT_SCHEMA_BOUNDS = {
39
+ maxBytes: 256 * 1024,
40
+ maxDepth: 32,
41
+ maxNodes: 4096,
42
+ };
43
+ function inputCapability(method) {
44
+ if (method === "elicitation/create")
45
+ return "elicitation";
46
+ if (method === "sampling/createMessage")
47
+ return "sampling";
48
+ return "roots";
49
+ }
50
+ function assertBoundedJson(value, maximumBytes, field) {
51
+ let serialized;
52
+ try {
53
+ serialized = JSON.stringify(value);
54
+ }
55
+ catch {
56
+ throw new PmMcpProtocolError(`Invalid ${field}: value is not JSON serializable`, PM_MCP_ERROR_CODES.invalidParams, { field });
57
+ }
58
+ if (Buffer.byteLength(serialized, "utf8") > maximumBytes) {
59
+ throw new PmMcpProtocolError(`Invalid ${field}: payload exceeds the protocol bound`, PM_MCP_ERROR_CODES.invalidParams, { field, maximumBytes });
60
+ }
61
+ }
62
+ /** Validate and clone a server-authored MRTR request map. */
63
+ export function parseMcpInputRequests(value, requestContext) {
64
+ if (!isMcpRecord(value)) {
65
+ throw new PmMcpProtocolError("Invalid MCP inputRequests", PM_MCP_ERROR_CODES.invalidParams, { field: "inputRequests", expected: "object" });
66
+ }
67
+ const entries = Object.entries(value);
68
+ if (entries.length === 0 || entries.length > MAX_INPUT_REQUESTS) {
69
+ throw new PmMcpProtocolError("Invalid MCP inputRequests count", PM_MCP_ERROR_CODES.invalidParams, { minimum: 1, maximum: MAX_INPUT_REQUESTS, observed: entries.length });
70
+ }
71
+ const parsed = {};
72
+ for (const [key, request] of entries) {
73
+ if (!INPUT_KEY_PATTERN.test(key) || !isMcpRecord(request)) {
74
+ throw new PmMcpProtocolError("Invalid MCP input request entry", PM_MCP_ERROR_CODES.invalidParams, { field: `inputRequests.${key}` });
75
+ }
76
+ const method = request.method;
77
+ if (typeof method !== "string" ||
78
+ !PM_MCP_INPUT_REQUEST_METHODS.includes(method)) {
79
+ throw new PmMcpProtocolError("Unsupported MCP input request method", PM_MCP_ERROR_CODES.invalidParams, { field: `inputRequests.${key}.method`, method: method ?? null });
80
+ }
81
+ const capability = inputCapability(method);
82
+ if (!Object.prototype.hasOwnProperty.call(requestContext.clientCapabilities, capability)) {
83
+ throw new PmMcpProtocolError("Missing required client capability", PM_MCP_ERROR_CODES.missingRequiredClientCapability, { requiredCapabilities: { [capability]: {} } });
84
+ }
85
+ if (!isMcpRecord(request.params)) {
86
+ throw new PmMcpProtocolError("Invalid MCP input request parameters", PM_MCP_ERROR_CODES.invalidParams, { field: `inputRequests.${key}.params`, expected: "object" });
87
+ }
88
+ parsed[key] = {
89
+ method: method,
90
+ params: structuredClone(request.params),
91
+ };
92
+ }
93
+ assertBoundedJson(parsed, MAX_INPUT_PAYLOAD_BYTES, "inputRequests");
94
+ return parsed;
95
+ }
96
+ /** Validate and clone client-supplied input responses from an MRTR retry. */
97
+ export function parseMcpInputResponses(value) {
98
+ if (!isMcpRecord(value)) {
99
+ throw new PmMcpProtocolError("Invalid MCP inputResponses", PM_MCP_ERROR_CODES.invalidParams, { field: "inputResponses", expected: "object" });
100
+ }
101
+ const entries = Object.entries(value);
102
+ if (entries.length > MAX_INPUT_REQUESTS) {
103
+ throw new PmMcpProtocolError("Invalid MCP inputResponses count", PM_MCP_ERROR_CODES.invalidParams, { maximum: MAX_INPUT_REQUESTS, observed: entries.length });
104
+ }
105
+ const parsed = {};
106
+ for (const [key, response] of entries) {
107
+ if (!INPUT_KEY_PATTERN.test(key) || !isMcpRecord(response)) {
108
+ throw new PmMcpProtocolError("Invalid MCP input response entry", PM_MCP_ERROR_CODES.invalidParams, { field: `inputResponses.${key}` });
109
+ }
110
+ parsed[key] = structuredClone(response);
111
+ }
112
+ assertBoundedJson(parsed, MAX_INPUT_PAYLOAD_BYTES, "inputResponses");
113
+ return parsed;
114
+ }
115
+ /** Build a modern input-required result after validating capability and size bounds. */
116
+ export function buildMcpInputRequiredResult(input) {
117
+ const requestState = input.requestState?.trim();
118
+ if (requestState &&
119
+ Buffer.byteLength(requestState, "utf8") > MAX_REQUEST_STATE_BYTES) {
120
+ throw new PmMcpProtocolError("Invalid MCP requestState: payload exceeds the protocol bound", PM_MCP_ERROR_CODES.invalidParams, { field: "requestState", maximumBytes: MAX_REQUEST_STATE_BYTES });
121
+ }
122
+ const inputRequests = input.inputRequests === undefined
123
+ ? undefined
124
+ : parseMcpInputRequests(input.inputRequests, input.requestContext);
125
+ if (inputRequests === undefined && !requestState) {
126
+ throw new PmMcpProtocolError("InputRequiredResult requires inputRequests or requestState", PM_MCP_ERROR_CODES.invalidParams, { requiredAnyOf: ["inputRequests", "requestState"] });
127
+ }
128
+ return {
129
+ resultType: "input_required",
130
+ ...(inputRequests ? { inputRequests } : {}),
131
+ ...(requestState ? { requestState } : {}),
132
+ _meta: {
133
+ [PM_MCP_META_KEYS.serverInfo]: { ...input.serverInfo },
134
+ },
135
+ };
136
+ }
137
+ function requestStateSecret(secret) {
138
+ const bytes = Buffer.from(secret);
139
+ if (bytes.byteLength < 32) {
140
+ throw new PmMcpProtocolError("MCP requestState signing key must contain at least 32 bytes", PM_MCP_ERROR_CODES.invalidParams, { minimumBytes: 32 });
141
+ }
142
+ return bytes;
143
+ }
144
+ /** Seal integrity-protected continuation state for an MRTR retry. */
145
+ export function sealMcpRequestState(payload, secret) {
146
+ if (!Number.isSafeInteger(payload.expiresAt) ||
147
+ payload.expiresAt <= 0 ||
148
+ payload.method.trim().length === 0 ||
149
+ payload.parameterDigest.trim().length === 0 ||
150
+ payload.principal.trim().length === 0) {
151
+ throw new PmMcpProtocolError("Invalid MCP requestState payload", PM_MCP_ERROR_CODES.invalidParams);
152
+ }
153
+ const encoded = Buffer.from(JSON.stringify({ version: 1, ...payload }), "utf8");
154
+ if (encoded.byteLength > MAX_REQUEST_STATE_BYTES / 2) {
155
+ throw new PmMcpProtocolError("MCP requestState payload exceeds the protocol bound", PM_MCP_ERROR_CODES.invalidParams, { maximumBytes: MAX_REQUEST_STATE_BYTES / 2 });
156
+ }
157
+ const body = encoded.toString("base64url");
158
+ const signature = createHmac("sha256", requestStateSecret(secret))
159
+ .update(body)
160
+ .digest("base64url");
161
+ return `${body}.${signature}`;
162
+ }
163
+ function parseMcpRequestStatePayload(decoded) {
164
+ if (!isMcpRecord(decoded) || decoded.version !== 1) {
165
+ throw new PmMcpProtocolError("Invalid MCP requestState payload", PM_MCP_ERROR_CODES.invalidParams, { field: "requestState" });
166
+ }
167
+ const { expiresAt, method, parameterDigest, principal, state } = decoded;
168
+ if (typeof expiresAt !== "number" || !Number.isSafeInteger(expiresAt)) {
169
+ throw new PmMcpProtocolError("Invalid MCP requestState payload", PM_MCP_ERROR_CODES.invalidParams, { field: "requestState" });
170
+ }
171
+ if (typeof method !== "string" ||
172
+ typeof parameterDigest !== "string" ||
173
+ typeof principal !== "string") {
174
+ throw new PmMcpProtocolError("Invalid MCP requestState payload", PM_MCP_ERROR_CODES.invalidParams, { field: "requestState" });
175
+ }
176
+ return { expiresAt, method, parameterDigest, principal, state };
177
+ }
178
+ /** Verify an MRTR requestState value against method, principal, digest, and expiry. */
179
+ export function openMcpRequestState(value, secret, expected) {
180
+ const [body, signature, extra] = value.split(".");
181
+ if (!body || !signature || extra !== undefined) {
182
+ throw new PmMcpProtocolError("Invalid MCP requestState encoding", PM_MCP_ERROR_CODES.invalidParams, { field: "requestState" });
183
+ }
184
+ const observed = Buffer.from(signature, "base64url");
185
+ const calculated = createHmac("sha256", requestStateSecret(secret))
186
+ .update(body)
187
+ .digest();
188
+ if (observed.byteLength !== calculated.byteLength ||
189
+ !timingSafeEqual(observed, calculated)) {
190
+ throw new PmMcpProtocolError("Invalid MCP requestState signature", PM_MCP_ERROR_CODES.invalidParams, { field: "requestState" });
191
+ }
192
+ let decoded;
193
+ try {
194
+ decoded = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
195
+ }
196
+ catch {
197
+ decoded = null;
198
+ }
199
+ const payload = parseMcpRequestStatePayload(decoded);
200
+ const { expiresAt, method, parameterDigest, principal } = payload;
201
+ if (expiresAt < (expected.nowMs ?? Date.now())) {
202
+ throw new PmMcpProtocolError("Expired MCP requestState", PM_MCP_ERROR_CODES.invalidParams, { field: "requestState", expiredAt: expiresAt });
203
+ }
204
+ if (method !== expected.method ||
205
+ parameterDigest !== expected.parameterDigest ||
206
+ principal !== expected.principal) {
207
+ throw new PmMcpProtocolError("MCP requestState binding mismatch", PM_MCP_ERROR_CODES.invalidParams, { field: "requestState" });
208
+ }
209
+ return payload;
210
+ }
211
+ /** Compute a stable-sized digest for application-selected salient request data. */
212
+ export function digestMcpRequestParameters(value) {
213
+ assertBoundedJson(value, MAX_INPUT_PAYLOAD_BYTES, "request parameters");
214
+ return createHash("sha256").update(JSON.stringify(value)).digest("hex");
215
+ }
216
+ /**
217
+ * Bound single-use MRTR state consumption within one server process. Callers
218
+ * requiring cross-process one-time semantics should persist the resulting hash.
219
+ */
220
+ export class PmMcpRequestStateReplayGuard {
221
+ #consumed = new Set();
222
+ #maximumEntries;
223
+ /** Create a bounded in-process replay guard. */
224
+ constructor(maximumEntries = 4096) {
225
+ if (!Number.isSafeInteger(maximumEntries) || maximumEntries < 1) {
226
+ throw new PmMcpProtocolError("Invalid MCP replay guard capacity", PM_MCP_ERROR_CODES.invalidParams, { maximumEntries });
227
+ }
228
+ this.#maximumEntries = maximumEntries;
229
+ }
230
+ /** Consume one opaque requestState value exactly once in this process. */
231
+ consume(value) {
232
+ const digest = createHash("sha256").update(value).digest("hex");
233
+ if (this.#consumed.has(digest)) {
234
+ throw new PmMcpProtocolError("MCP requestState replay detected", PM_MCP_ERROR_CODES.invalidParams, { field: "requestState" });
235
+ }
236
+ if (this.#consumed.size >= this.#maximumEntries) {
237
+ const oldest = this.#consumed.values().next().value;
238
+ this.#consumed.delete(oldest);
239
+ }
240
+ this.#consumed.add(digest);
241
+ }
242
+ }
243
+ /** Validate and clone a required MCP cache policy. */
244
+ export function parseMcpCachePolicy(value) {
245
+ if (!Number.isSafeInteger(value.ttlMs) ||
246
+ value.ttlMs < 0 ||
247
+ (value.cacheScope !== "public" && value.cacheScope !== "private")) {
248
+ throw new PmMcpProtocolError("Invalid MCP cache policy", PM_MCP_ERROR_CODES.invalidParams, { ttlMs: value.ttlMs, cacheScope: value.cacheScope });
249
+ }
250
+ return { ttlMs: value.ttlMs, cacheScope: value.cacheScope };
251
+ }
252
+ /** Attach required cache fields without mutating a method-specific payload. */
253
+ export function withMcpCachePolicy(payload, policy) {
254
+ return { ...payload, ...parseMcpCachePolicy(policy) };
255
+ }
256
+ function decodeJsonPointerToken(value) {
257
+ return value.replaceAll("~1", "/").replaceAll("~0", "~");
258
+ }
259
+ function resolveLocalJsonSchemaReference(root, reference) {
260
+ if (reference === "#")
261
+ return root;
262
+ if (!reference.startsWith("#/"))
263
+ return undefined;
264
+ let current = root;
265
+ for (const token of reference
266
+ .slice(2)
267
+ .split("/")
268
+ .map(decodeJsonPointerToken)) {
269
+ if (!isMcpRecord(current) && !Array.isArray(current))
270
+ return undefined;
271
+ if (!Object.prototype.hasOwnProperty.call(current, token))
272
+ return undefined;
273
+ current = current[token];
274
+ }
275
+ return current;
276
+ }
277
+ function resolveMcpJsonSchemaBounds(bounds) {
278
+ const maximumBytes = bounds.maxBytes ?? DEFAULT_SCHEMA_BOUNDS.maxBytes;
279
+ const maximumDepth = bounds.maxDepth ?? DEFAULT_SCHEMA_BOUNDS.maxDepth;
280
+ const maximumNodes = bounds.maxNodes ?? DEFAULT_SCHEMA_BOUNDS.maxNodes;
281
+ if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 2) {
282
+ throw new PmMcpProtocolError("Invalid MCP JSON Schema work bounds", PM_MCP_ERROR_CODES.invalidParams);
283
+ }
284
+ if (!Number.isSafeInteger(maximumDepth) || maximumDepth < 1) {
285
+ throw new PmMcpProtocolError("Invalid MCP JSON Schema work bounds", PM_MCP_ERROR_CODES.invalidParams);
286
+ }
287
+ if (!Number.isSafeInteger(maximumNodes) || maximumNodes < 1) {
288
+ throw new PmMcpProtocolError("Invalid MCP JSON Schema work bounds", PM_MCP_ERROR_CODES.invalidParams);
289
+ }
290
+ return { maximumBytes, maximumDepth, maximumNodes };
291
+ }
292
+ function enqueueMcpJsonSchemaChildren(current, pending) {
293
+ const entries = Array.isArray(current.value)
294
+ ? current.value
295
+ : isMcpRecord(current.value)
296
+ ? Object.values(current.value)
297
+ : [];
298
+ for (const entry of entries) {
299
+ pending.push({ value: entry, depth: current.depth + 1 });
300
+ }
301
+ }
302
+ function assertMcpJsonSchemaReference(root, value) {
303
+ if (!isMcpRecord(value) || typeof value.$ref !== "string")
304
+ return;
305
+ const reference = value.$ref;
306
+ if (reference.startsWith("#") &&
307
+ resolveLocalJsonSchemaReference(root, reference) === undefined) {
308
+ throw new PmMcpProtocolError("MCP JSON Schema contains an unresolved local reference", PM_MCP_ERROR_CODES.invalidParams, { reference });
309
+ }
310
+ }
311
+ /**
312
+ * Validate JSON Schema 2020-12 structure under explicit byte, depth, node, and
313
+ * local-reference work bounds while allowing the complete keyword vocabulary.
314
+ */
315
+ export function validateMcpJsonSchema(schema, bounds = {}) {
316
+ const { maximumBytes, maximumDepth, maximumNodes } = resolveMcpJsonSchemaBounds(bounds);
317
+ if (typeof schema !== "boolean" && !isMcpRecord(schema)) {
318
+ throw new PmMcpProtocolError("Invalid MCP JSON Schema root", PM_MCP_ERROR_CODES.invalidParams, { expected: "object or boolean" });
319
+ }
320
+ assertBoundedJson(schema, maximumBytes, "JSON Schema");
321
+ const pending = [
322
+ { value: schema, depth: 0 },
323
+ ];
324
+ let visited = 0;
325
+ while (pending.length > 0) {
326
+ const current = pending.pop();
327
+ visited += 1;
328
+ if (visited > maximumNodes || current.depth > maximumDepth) {
329
+ throw new PmMcpProtocolError("MCP JSON Schema exceeds validation work bounds", PM_MCP_ERROR_CODES.invalidParams, { maximumDepth, maximumNodes });
330
+ }
331
+ assertMcpJsonSchemaReference(schema, current.value);
332
+ enqueueMcpJsonSchemaChildren(current, pending);
333
+ }
334
+ return structuredClone(schema);
335
+ }
336
+ //# sourceMappingURL=interactions.js.map
337
+ //# debugId=469f704b-12eb-524d-bcc8-fb8f9f1775f2
@@ -0,0 +1,142 @@
1
+ /**
2
+ * @module sdk/mcp/protocol
3
+ *
4
+ * Defines transport-neutral MCP 2026-07-28 negotiation, request metadata,
5
+ * discovery, result-envelope, and bounded legacy-compatibility contracts.
6
+ */
7
+ /** Canonical stateless MCP revision implemented by pm. */
8
+ export declare const PM_MCP_PROTOCOL_VERSION: "2026-07-28";
9
+ /** Legacy initialize-era revisions accepted only by the bounded stdio adapter. */
10
+ export declare const PM_MCP_LEGACY_PROTOCOL_VERSIONS: readonly ["2025-06-18"];
11
+ /** Modern per-request protocol versions accepted by the stateless core. */
12
+ export declare const PM_MCP_SUPPORTED_PROTOCOL_VERSIONS: readonly ["2026-07-28"];
13
+ /** Allocated MCP 2026-07-28 protocol error codes. */
14
+ export declare const PM_MCP_ERROR_CODES: {
15
+ readonly headerMismatch: -32020;
16
+ readonly missingRequiredClientCapability: -32021;
17
+ readonly unsupportedProtocolVersion: -32022;
18
+ readonly invalidParams: -32602;
19
+ };
20
+ /** Namespaced metadata keys owned by the MCP specification. */
21
+ export declare const PM_MCP_META_KEYS: {
22
+ readonly clientCapabilities: "io.modelcontextprotocol/clientCapabilities";
23
+ readonly clientInfo: "io.modelcontextprotocol/clientInfo";
24
+ readonly protocolVersion: "io.modelcontextprotocol/protocolVersion";
25
+ readonly serverInfo: "io.modelcontextprotocol/serverInfo";
26
+ };
27
+ /** MCP implementation identity carried in request and result metadata. */
28
+ export interface PmMcpImplementation {
29
+ /** Stable implementation name. */
30
+ name: string;
31
+ /** Implementation version. */
32
+ version: string;
33
+ /** Optional human-readable implementation description. */
34
+ description?: string;
35
+ /** Optional implementation website. */
36
+ websiteUrl?: string;
37
+ }
38
+ /** Open MCP client capability map declared independently on every request. */
39
+ export type PmMcpClientCapabilities = Record<string, unknown>;
40
+ /** Server capabilities advertised by pm discovery. */
41
+ export interface PmMcpServerCapabilities {
42
+ /** Prompt surface and change-notification support. */
43
+ prompts?: {
44
+ listChanged?: boolean;
45
+ };
46
+ /** Resource surface and change-notification support. */
47
+ resources?: {
48
+ listChanged?: boolean;
49
+ subscribe?: boolean;
50
+ };
51
+ /** Tool surface and change-notification support. */
52
+ tools?: {
53
+ listChanged?: boolean;
54
+ };
55
+ /** Negotiated optional extension settings keyed by extension identifier. */
56
+ extensions?: Record<string, Record<string, unknown>>;
57
+ /** Additional capability declarations retained for forward compatibility. */
58
+ [key: string]: unknown;
59
+ }
60
+ /** Validated request-local metadata for one modern MCP operation. */
61
+ export interface PmMcpRequestContext {
62
+ /** Exact modern protocol revision used by this request. */
63
+ protocolVersion: (typeof PM_MCP_SUPPORTED_PROTOCOL_VERSIONS)[number];
64
+ /** Capabilities declared for this request only. */
65
+ clientCapabilities: PmMcpClientCapabilities;
66
+ /** Optional bounded client identity used only for diagnostics/provenance. */
67
+ clientInfo?: PmMcpImplementation;
68
+ }
69
+ /** Required fields attached to every modern successful result. */
70
+ export interface PmMcpResultEnvelope {
71
+ /** Ordinary successful results are complete. */
72
+ resultType: "complete";
73
+ /** Result-local MCP metadata. */
74
+ _meta: {
75
+ /** Server identity is repeated on every modern result. */
76
+ "io.modelcontextprotocol/serverInfo": PmMcpImplementation;
77
+ };
78
+ /** Additional method-specific result fields. */
79
+ [key: string]: unknown;
80
+ }
81
+ /** Required server identity metadata attached to every modern result shape. */
82
+ export interface PmMcpServerResultMetadata {
83
+ /** Result-local MCP metadata. */
84
+ _meta: {
85
+ /** Server identity is repeated on every modern result. */
86
+ "io.modelcontextprotocol/serverInfo": PmMcpImplementation;
87
+ /** Additional namespaced or application metadata. */
88
+ [key: string]: unknown;
89
+ };
90
+ }
91
+ /** Modern discovery response contract. */
92
+ export interface PmMcpDiscoverResult extends PmMcpResultEnvelope {
93
+ /** Modern stateless revisions accepted through per-request metadata. */
94
+ supportedVersions: string[];
95
+ /** Deterministic server capability declaration. */
96
+ capabilities: PmMcpServerCapabilities;
97
+ /** Cache freshness hint required by the current schema. */
98
+ ttlMs: number;
99
+ /** Discovery is public because it contains no caller-specific data. */
100
+ cacheScope: "public";
101
+ /** Optional model-facing usage guidance. */
102
+ instructions?: string;
103
+ }
104
+ /** Protocol-era interpretation used at explicit compatibility boundaries. */
105
+ export type PmMcpProtocolEra = "modern" | "legacy";
106
+ /** Structured MCP protocol error safe for JSON-RPC adapters. */
107
+ export declare class PmMcpProtocolError extends Error {
108
+ /** JSON-RPC/MCP error code. */
109
+ readonly code: number;
110
+ /** Structured recovery or mismatch detail. */
111
+ readonly data: Record<string, unknown>;
112
+ /** Create one typed protocol error. */
113
+ constructor(message: string, code: number, data?: Record<string, unknown>);
114
+ }
115
+ /** Return whether an unknown value is a non-array object. */
116
+ export declare function isMcpRecord(value: unknown): value is Record<string, unknown>;
117
+ /** Parse an optional MCP implementation identity without guessing missing fields. */
118
+ export declare function parseMcpImplementation(value: unknown): PmMcpImplementation | undefined;
119
+ /** Validate the stateless metadata required on every modern MCP request. */
120
+ export declare function resolveMcpRequestContext(params: unknown): PmMcpRequestContext;
121
+ /** Validate the HTTP protocol-version header against request-local metadata. */
122
+ export declare function assertMcpProtocolHeader(requestContext: PmMcpRequestContext, headerValue: string | undefined): void;
123
+ /** Require named client capabilities without consulting prior requests. */
124
+ export declare function assertMcpClientCapabilities(requestContext: PmMcpRequestContext, requiredCapabilities: readonly string[]): void;
125
+ /** Return whether this request independently negotiated one named extension. */
126
+ export declare function hasMcpClientExtension(requestContext: PmMcpRequestContext, extension: string): boolean;
127
+ /** Attach required server identity while preserving a non-complete result discriminator. */
128
+ export declare function attachMcpServerInfo<Payload extends Record<string, unknown>>(payload: Payload, serverInfo: PmMcpImplementation): Payload & PmMcpServerResultMetadata;
129
+ /** Attach required modern result fields without mutating the caller payload. */
130
+ export declare function buildMcpCompleteResult<Payload extends Record<string, unknown>>(payload: Payload, serverInfo: PmMcpImplementation): Payload & PmMcpResultEnvelope;
131
+ /** Build deterministic current-revision server discovery. */
132
+ export declare function buildMcpDiscoverResult(input: {
133
+ serverInfo: PmMcpImplementation;
134
+ capabilities: PmMcpServerCapabilities;
135
+ instructions?: string;
136
+ ttlMs?: number;
137
+ }): PmMcpDiscoverResult;
138
+ /**
139
+ * Interpret resultType only at an explicit protocol-era boundary. Legacy
140
+ * results may omit it; modern results fail closed when it is absent.
141
+ */
142
+ export declare function interpretMcpResultType(result: unknown, era: PmMcpProtocolEra): string;
@@ -0,0 +1,174 @@
1
+ /**
2
+ * @module sdk/mcp/protocol
3
+ *
4
+ * Defines transport-neutral MCP 2026-07-28 negotiation, request metadata,
5
+ * discovery, result-envelope, and bounded legacy-compatibility contracts.
6
+ */
7
+ /** Canonical stateless MCP revision implemented by pm. */
8
+
9
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="9cb05a78-f95d-5211-a35a-03756f66c812")}catch(e){}}();
10
+ export const PM_MCP_PROTOCOL_VERSION = "2026-07-28";
11
+ /** Legacy initialize-era revisions accepted only by the bounded stdio adapter. */
12
+ export const PM_MCP_LEGACY_PROTOCOL_VERSIONS = ["2025-06-18"];
13
+ /** Modern per-request protocol versions accepted by the stateless core. */
14
+ export const PM_MCP_SUPPORTED_PROTOCOL_VERSIONS = [
15
+ PM_MCP_PROTOCOL_VERSION,
16
+ ];
17
+ /** Allocated MCP 2026-07-28 protocol error codes. */
18
+ export const PM_MCP_ERROR_CODES = {
19
+ headerMismatch: -32020,
20
+ missingRequiredClientCapability: -32021,
21
+ unsupportedProtocolVersion: -32022,
22
+ invalidParams: -32602,
23
+ };
24
+ /** Namespaced metadata keys owned by the MCP specification. */
25
+ export const PM_MCP_META_KEYS = {
26
+ clientCapabilities: "io.modelcontextprotocol/clientCapabilities",
27
+ clientInfo: "io.modelcontextprotocol/clientInfo",
28
+ protocolVersion: "io.modelcontextprotocol/protocolVersion",
29
+ serverInfo: "io.modelcontextprotocol/serverInfo",
30
+ };
31
+ /** Structured MCP protocol error safe for JSON-RPC adapters. */
32
+ export class PmMcpProtocolError extends Error {
33
+ /** JSON-RPC/MCP error code. */
34
+ code;
35
+ /** Structured recovery or mismatch detail. */
36
+ data;
37
+ /** Create one typed protocol error. */
38
+ constructor(message, code, data = {}) {
39
+ super(message);
40
+ this.name = "PmMcpProtocolError";
41
+ this.code = code;
42
+ this.data = data;
43
+ }
44
+ }
45
+ /** Return whether an unknown value is a non-array object. */
46
+ export function isMcpRecord(value) {
47
+ return typeof value === "object" && value !== null && !Array.isArray(value);
48
+ }
49
+ /** Parse an optional MCP implementation identity without guessing missing fields. */
50
+ export function parseMcpImplementation(value) {
51
+ if (value === undefined)
52
+ return undefined;
53
+ if (!isMcpRecord(value)) {
54
+ throw new PmMcpProtocolError("Invalid MCP clientInfo metadata", PM_MCP_ERROR_CODES.invalidParams, { field: PM_MCP_META_KEYS.clientInfo, expected: "object" });
55
+ }
56
+ const name = typeof value.name === "string" ? value.name.trim() : "";
57
+ const version = typeof value.version === "string" ? value.version.trim() : "";
58
+ if (name.length === 0 || version.length === 0) {
59
+ throw new PmMcpProtocolError("Invalid MCP clientInfo metadata", PM_MCP_ERROR_CODES.invalidParams, {
60
+ field: PM_MCP_META_KEYS.clientInfo,
61
+ required: ["name", "version"],
62
+ });
63
+ }
64
+ const parsed = {
65
+ name: name.slice(0, 128),
66
+ version: version.slice(0, 128),
67
+ };
68
+ if (typeof value.description === "string" && value.description.trim()) {
69
+ parsed.description = value.description.trim().slice(0, 1024);
70
+ }
71
+ if (typeof value.websiteUrl === "string" && value.websiteUrl.trim()) {
72
+ parsed.websiteUrl = value.websiteUrl.trim().slice(0, 2048);
73
+ }
74
+ return parsed;
75
+ }
76
+ /** Validate the stateless metadata required on every modern MCP request. */
77
+ export function resolveMcpRequestContext(params) {
78
+ const meta = isMcpRecord(params) ? params._meta : undefined;
79
+ if (!isMcpRecord(meta)) {
80
+ throw new PmMcpProtocolError("Missing required MCP request metadata", PM_MCP_ERROR_CODES.invalidParams, {
81
+ required: [
82
+ PM_MCP_META_KEYS.protocolVersion,
83
+ PM_MCP_META_KEYS.clientCapabilities,
84
+ ],
85
+ });
86
+ }
87
+ const requested = meta[PM_MCP_META_KEYS.protocolVersion];
88
+ if (typeof requested !== "string" ||
89
+ !PM_MCP_SUPPORTED_PROTOCOL_VERSIONS.includes(requested)) {
90
+ throw new PmMcpProtocolError("Unsupported protocol version", PM_MCP_ERROR_CODES.unsupportedProtocolVersion, {
91
+ supported: [...PM_MCP_SUPPORTED_PROTOCOL_VERSIONS],
92
+ requested: typeof requested === "string" ? requested : null,
93
+ });
94
+ }
95
+ const clientCapabilities = meta[PM_MCP_META_KEYS.clientCapabilities];
96
+ if (!isMcpRecord(clientCapabilities)) {
97
+ throw new PmMcpProtocolError("Invalid MCP client capabilities metadata", PM_MCP_ERROR_CODES.invalidParams, {
98
+ field: PM_MCP_META_KEYS.clientCapabilities,
99
+ expected: "object",
100
+ });
101
+ }
102
+ const clientInfo = parseMcpImplementation(meta[PM_MCP_META_KEYS.clientInfo]);
103
+ return {
104
+ protocolVersion: PM_MCP_PROTOCOL_VERSION,
105
+ clientCapabilities,
106
+ ...(clientInfo ? { clientInfo } : {}),
107
+ };
108
+ }
109
+ /** Validate the HTTP protocol-version header against request-local metadata. */
110
+ export function assertMcpProtocolHeader(requestContext, headerValue) {
111
+ if (headerValue !== requestContext.protocolVersion) {
112
+ throw new PmMcpProtocolError("MCP protocol header does not match request metadata", PM_MCP_ERROR_CODES.headerMismatch, {
113
+ header: headerValue ?? null,
114
+ metadata: requestContext.protocolVersion,
115
+ });
116
+ }
117
+ }
118
+ /** Require named client capabilities without consulting prior requests. */
119
+ export function assertMcpClientCapabilities(requestContext, requiredCapabilities) {
120
+ const missing = requiredCapabilities.filter((capability) => !Object.prototype.hasOwnProperty.call(requestContext.clientCapabilities, capability));
121
+ if (missing.length > 0) {
122
+ throw new PmMcpProtocolError("Missing required client capability", PM_MCP_ERROR_CODES.missingRequiredClientCapability, {
123
+ requiredCapabilities: Object.fromEntries(missing.map((capability) => [capability, {}])),
124
+ });
125
+ }
126
+ }
127
+ /** Return whether this request independently negotiated one named extension. */
128
+ export function hasMcpClientExtension(requestContext, extension) {
129
+ const extensions = requestContext.clientCapabilities.extensions;
130
+ return isMcpRecord(extensions) && isMcpRecord(extensions[extension]);
131
+ }
132
+ /** Attach required server identity while preserving a non-complete result discriminator. */
133
+ export function attachMcpServerInfo(payload, serverInfo) {
134
+ const payloadMeta = isMcpRecord(payload._meta) ? payload._meta : {};
135
+ return {
136
+ ...payload,
137
+ _meta: {
138
+ ...payloadMeta,
139
+ [PM_MCP_META_KEYS.serverInfo]: { ...serverInfo },
140
+ },
141
+ };
142
+ }
143
+ /** Attach required modern result fields without mutating the caller payload. */
144
+ export function buildMcpCompleteResult(payload, serverInfo) {
145
+ return attachMcpServerInfo({ ...payload, resultType: "complete" }, serverInfo);
146
+ }
147
+ /** Build deterministic current-revision server discovery. */
148
+ export function buildMcpDiscoverResult(input) {
149
+ const ttlMs = input.ttlMs ?? 60_000;
150
+ if (!Number.isFinite(ttlMs) || ttlMs < 0) {
151
+ throw new PmMcpProtocolError("Invalid MCP discovery cache TTL", PM_MCP_ERROR_CODES.invalidParams, { ttlMs });
152
+ }
153
+ return buildMcpCompleteResult({
154
+ supportedVersions: [...PM_MCP_SUPPORTED_PROTOCOL_VERSIONS],
155
+ capabilities: structuredClone(input.capabilities),
156
+ ttlMs,
157
+ cacheScope: "public",
158
+ ...(input.instructions ? { instructions: input.instructions } : {}),
159
+ }, input.serverInfo);
160
+ }
161
+ /**
162
+ * Interpret resultType only at an explicit protocol-era boundary. Legacy
163
+ * results may omit it; modern results fail closed when it is absent.
164
+ */
165
+ export function interpretMcpResultType(result, era) {
166
+ if (isMcpRecord(result) && typeof result.resultType === "string") {
167
+ return result.resultType;
168
+ }
169
+ if (era === "legacy")
170
+ return "complete";
171
+ throw new PmMcpProtocolError("Modern MCP result is missing resultType", PM_MCP_ERROR_CODES.invalidParams, { required: "resultType" });
172
+ }
173
+ //# sourceMappingURL=protocol.js.map
174
+ //# debugId=9cb05a78-f95d-5211-a35a-03756f66c812