pico-engine 1.9.5 → 1.10.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 (126) hide show
  1. package/README.md +11 -5
  2. package/demos/bootstrap/com.example.visitors.bootstrap.krl +9 -5
  3. package/demos/child_tasks/com.example.task_runner.bootstrap.krl +10 -7
  4. package/demos/echo/com.example.echo.bootstrap.krl +10 -7
  5. package/demos/guard_rules/com.example.archive.bootstrap.krl +10 -7
  6. package/demos/json_query/README.md +11 -0
  7. package/demos/json_query/com.example.json_query.bootstrap.krl +84 -0
  8. package/demos/json_query/com.example.json_query.krl +162 -0
  9. package/demos/json_query/try-it.md +5 -0
  10. package/demos/kblog/com.example.kblog.bootstrap.krl +10 -7
  11. package/demos/layered_rulesets/com.example.invitations.bootstrap.krl +10 -7
  12. package/demos/score_tracker/com.example.score_tracker.bootstrap.krl +10 -7
  13. package/demos/secrets/com.example.notifier.bootstrap.krl +10 -7
  14. package/demos/try-it-order.json +1 -1
  15. package/demos/two_picos/com.example.two_picos.bootstrap.krl +5 -2
  16. package/demos/xmlui/com.example.thermostat.bootstrap.krl +10 -7
  17. package/dist/cli.js +5 -1
  18. package/dist/engineConfig.js +1 -1
  19. package/dist/identity/portableMove.js +5 -1
  20. package/dist/index.js +44 -12
  21. package/dist/internalAccess.js +110 -0
  22. package/dist/oauth/OAuthService.js +172 -10
  23. package/dist/oauth/acg.js +194 -24
  24. package/dist/oauth/cimd.js +381 -0
  25. package/dist/oauth/discovery.js +175 -0
  26. package/dist/runMcp.js +1 -1
  27. package/dist/server.js +197 -48
  28. package/dist/subtreeWrangler.js +8 -5
  29. package/dist/uiChannelPolicies.js +2 -0
  30. package/krl/io.picolabs.pds.krl +109 -21
  31. package/krl/io.picolabs.pico-engine-ui.krl +13 -7
  32. package/krl/io.picolabs.wrangler.krl +21 -9
  33. package/mcp/devResources.js +52 -0
  34. package/mcp/devTools.js +40 -9
  35. package/mcp/docs/CLAUDE.md +3 -2
  36. package/mcp/docs/cookbook/README.md +23 -0
  37. package/mcp/docs/cookbook/bootstrap/README.md +23 -0
  38. package/mcp/docs/cookbook/bootstrap/instructions.md +75 -0
  39. package/mcp/docs/cookbook/child_tasks/README.md +20 -0
  40. package/mcp/docs/cookbook/child_tasks/instructions.md +60 -0
  41. package/mcp/docs/cookbook/collection/README.md +21 -0
  42. package/mcp/docs/cookbook/collection/instructions.md +93 -0
  43. package/mcp/docs/cookbook/echo/README.md +19 -0
  44. package/mcp/docs/cookbook/echo/instructions.md +59 -0
  45. package/mcp/docs/cookbook/guard_rules/README.md +22 -0
  46. package/mcp/docs/cookbook/guard_rules/instructions.md +73 -0
  47. package/mcp/docs/cookbook/json_query/README.md +26 -0
  48. package/mcp/docs/cookbook/json_query/instructions.md +64 -0
  49. package/mcp/docs/cookbook/kblog/README.md +60 -0
  50. package/mcp/docs/cookbook/kblog/instructions.md +102 -0
  51. package/mcp/docs/cookbook/layered_rulesets/README.md +24 -0
  52. package/mcp/docs/cookbook/layered_rulesets/instructions.md +87 -0
  53. package/mcp/docs/cookbook/moving_picos/README.md +44 -0
  54. package/mcp/docs/cookbook/moving_picos/instructions.md +150 -0
  55. package/mcp/docs/cookbook/score_tracker/README.md +19 -0
  56. package/mcp/docs/cookbook/score_tracker/instructions.md +73 -0
  57. package/mcp/docs/cookbook/secrets/README.md +25 -0
  58. package/mcp/docs/cookbook/secrets/instructions.md +98 -0
  59. package/mcp/docs/cookbook/two_picos/README.md +20 -0
  60. package/mcp/docs/cookbook/two_picos/instructions.md +88 -0
  61. package/mcp/docs/cookbook/xmlui/README.md +23 -0
  62. package/mcp/docs/cookbook/xmlui/instructions.md +84 -0
  63. package/mcp/docs/developing/README.md +28 -0
  64. package/mcp/docs/developing/accepting-relationship-requests.md +65 -0
  65. package/mcp/docs/developing/arrays-and-maps.md +77 -0
  66. package/mcp/docs/developing/converting-time-formats.md +28 -0
  67. package/mcp/docs/developing/cookies-and-redirects.md +81 -0
  68. package/mcp/docs/developing/decoding-form-data.md +67 -0
  69. package/mcp/docs/developing/engine-log-files.md +34 -0
  70. package/mcp/docs/developing/event-loop.md +77 -0
  71. package/mcp/docs/developing/events-from-email.md +80 -0
  72. package/mcp/docs/developing/initializing-entity-variables.md +83 -0
  73. package/mcp/docs/developing/mcp-ai-tools.md +98 -0
  74. package/mcp/docs/developing/misconceptions.md +467 -0
  75. package/mcp/docs/developing/names-and-scope.md +44 -0
  76. package/mcp/docs/developing/postman.md +159 -0
  77. package/mcp/docs/developing/querying-another-pico.md +47 -0
  78. package/mcp/docs/developing/singleton-picos.md +36 -0
  79. package/mcp/docs/developing/tabular-data.md +67 -0
  80. package/mcp/docs/developing/tips.md +251 -0
  81. package/mcp/docs/developing/webhook-signatures.md +56 -0
  82. package/mcp/docs/developing/workflow.md +106 -0
  83. package/mcp/docs/exp/README.md +46 -0
  84. package/mcp/docs/exp/event.md +110 -0
  85. package/mcp/docs/exp/query.md +94 -0
  86. package/mcp/docs/lessons/README.md +59 -0
  87. package/mcp/docs/lessons/events-and-queries.md +247 -0
  88. package/mcp/docs/lessons/gossip.md +28 -0
  89. package/mcp/docs/lessons/modules-and-apis.md +270 -0
  90. package/mcp/docs/lessons/pico-based-systems.md +470 -0
  91. package/mcp/docs/lessons/pico-state.md +267 -0
  92. package/mcp/docs/lessons/pico-views.md +290 -0
  93. package/mcp/docs/lessons/quickstart.md +157 -0
  94. package/mcp/docs/lessons/relationships.md +530 -0
  95. package/mcp/docs/lessons/scatter-gather.md +362 -0
  96. package/mcp/docs/pico-engine.md +7 -5
  97. package/mcp/docs/pico-overview.md +3 -3
  98. package/mcp/docs/wrangler/README.md +47 -0
  99. package/mcp/docs/wrangler/channels.md +235 -0
  100. package/mcp/docs/wrangler/oauth.md +56 -0
  101. package/mcp/docs/wrangler/pds.md +423 -0
  102. package/mcp/docs/wrangler/portable-subtree.md +44 -0
  103. package/mcp/docs/wrangler/relationships.md +297 -0
  104. package/mcp/docs/wrangler/wrangler.md +253 -0
  105. package/mcp/docs/wrangler/xmlui.md +60 -0
  106. package/mcp/engineClient.js +57 -5
  107. package/mcp/mcpScopes.js +118 -0
  108. package/mcp/meshHttp.js +151 -45
  109. package/mcp/runStdio.js +2 -0
  110. package/mcp/subtreeTools.js +184 -0
  111. package/mcp/tryItTools.js +202 -0
  112. package/package.json +14 -8
  113. package/public/pico-engine-ui.js +26 -26
  114. package/src/cli.ts +6 -2
  115. package/src/engineConfig.ts +5 -2
  116. package/src/identity/portableMove.ts +6 -1
  117. package/src/index.ts +469 -430
  118. package/src/internalAccess.ts +127 -0
  119. package/src/oauth/OAuthService.ts +243 -11
  120. package/src/oauth/acg.ts +289 -25
  121. package/src/oauth/cimd.ts +508 -0
  122. package/src/oauth/discovery.ts +233 -0
  123. package/src/runMcp.ts +3 -1
  124. package/src/server.ts +252 -52
  125. package/src/subtreeWrangler.ts +17 -5
  126. package/src/uiChannelPolicies.ts +2 -0
@@ -1,7 +1,32 @@
1
1
  "use strict";
2
2
 
3
+ const fs = require("fs");
4
+ const os = require("os");
5
+ const path = require("path");
3
6
  const fetch = require("cross-fetch");
4
7
 
8
+ // Same file the engine writes in src/internalAccess.ts (INTERNAL_TOKEN_FILENAME).
9
+ const INTERNAL_TOKEN_FILENAME = "internal-token";
10
+
11
+ function engineHome() {
12
+ const fromEnv = process.env.PICO_ENGINE_HOME;
13
+ if (typeof fromEnv === "string" && fromEnv.length > 0) {
14
+ return fromEnv.replace(/^~(?=$|\/)/, os.homedir());
15
+ }
16
+ return path.join(os.homedir(), ".pico-engine");
17
+ }
18
+
19
+ function readInternalToken() {
20
+ try {
21
+ const token = fs
22
+ .readFileSync(path.join(engineHome(), INTERNAL_TOKEN_FILENAME), "utf8")
23
+ .trim();
24
+ return token.length > 0 ? token : "";
25
+ } catch (_err) {
26
+ return "";
27
+ }
28
+ }
29
+
5
30
  function normalizeBaseUrl(url) {
6
31
  return url.replace(/\/$/, "");
7
32
  }
@@ -18,8 +43,19 @@ class EngineClient {
18
43
  this.uiEciCached = undefined;
19
44
  }
20
45
 
46
+ internalHeaders(extra = {}) {
47
+ const headers = { ...extra };
48
+ const token = readInternalToken();
49
+ if (token) {
50
+ headers["X-Pico-Internal"] = token;
51
+ }
52
+ return headers;
53
+ }
54
+
21
55
  async getDevLocal() {
22
- const res = await fetch(`${this.baseUrl}/api/dev/local`);
56
+ const res = await fetch(`${this.baseUrl}/api/dev/local`, {
57
+ headers: this.internalHeaders(),
58
+ });
23
59
  if (!res.ok) {
24
60
  const text = await res.text();
25
61
  throw new Error(`GET /api/dev/local ${res.status}: ${text}`);
@@ -28,7 +64,9 @@ class EngineClient {
28
64
  }
29
65
 
30
66
  async getUiContext() {
31
- const res = await fetch(`${this.baseUrl}/api/ui-context`);
67
+ const res = await fetch(`${this.baseUrl}/api/ui-context`, {
68
+ headers: this.internalHeaders(),
69
+ });
32
70
  if (!res.ok) {
33
71
  throw new Error(`GET /api/ui-context ${res.status}`);
34
72
  }
@@ -57,7 +95,7 @@ class EngineClient {
57
95
  return ctx.eci;
58
96
  }
59
97
  throw new Error(
60
- "Could not resolve UI channel ECI. Set PICO_ENGINE_UI_ECI, sign in via the UI (same engine), or use localhost with PICO_ENGINE_ALLOW_LOCALHOST_C unset."
98
+ "Could not resolve UI channel ECI. Set PICO_ENGINE_UI_ECI, or point PICO_ENGINE_HOME at the running engine's data directory so the internal token can be read."
61
99
  );
62
100
  }
63
101
 
@@ -66,7 +104,9 @@ class EngineClient {
66
104
  `${this.baseUrl}/c/${encodeURIComponent(eci)}/query/${encodeURIComponent(rid)}/${encodeURIComponent(name)}`,
67
105
  {
68
106
  method: "POST",
69
- headers: { "Content-Type": "application/json; charset=utf-8" },
107
+ headers: this.internalHeaders({
108
+ "Content-Type": "application/json; charset=utf-8",
109
+ }),
70
110
  body: JSON.stringify(args),
71
111
  }
72
112
  );
@@ -88,7 +128,9 @@ class EngineClient {
88
128
  `${this.baseUrl}/c/${encodeURIComponent(eci)}/event-wait/${encodeURIComponent(domain)}/${encodeURIComponent(name)}`,
89
129
  {
90
130
  method: "POST",
91
- headers: { "Content-Type": "application/json; charset=utf-8" },
131
+ headers: this.internalHeaders({
132
+ "Content-Type": "application/json; charset=utf-8",
133
+ }),
92
134
  body: JSON.stringify(attrs),
93
135
  }
94
136
  );
@@ -97,6 +139,16 @@ class EngineClient {
97
139
  return JSON.parse(text);
98
140
  }
99
141
 
142
+ async getTryIt() {
143
+ const res = await fetch(`${this.baseUrl}/api/try-it`, {
144
+ headers: this.internalHeaders(),
145
+ });
146
+ if (!res.ok) {
147
+ throw new Error(`GET /api/try-it ${res.status}`);
148
+ }
149
+ return res.json();
150
+ }
151
+
100
152
  async engineUiEvent(name, attrs = {}) {
101
153
  const ui = await this.resolveUiEci();
102
154
  return this.channelEventWait(ui, "engine_ui", name, attrs);
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+
3
+ const READ = "mesh:read";
4
+ const ACT = "mesh:act";
5
+
6
+ function granted(scope) {
7
+ return new Set(String(scope || "").split(/\s+/).filter(Boolean));
8
+ }
9
+
10
+ function has(scope, name) {
11
+ return granted(scope).has(name);
12
+ }
13
+
14
+ function hasOperational(scope) {
15
+ return has(scope, READ) || has(scope, ACT);
16
+ }
17
+
18
+ function mcpSurfaceAllowed(policy, surface) {
19
+ const rules = policy || { allow: [], deny: [] };
20
+ const denied = (rules.deny || []).some(
21
+ (rule) => rule && (rule.surface === "*" || rule.surface === surface)
22
+ );
23
+ if (denied) {
24
+ return false;
25
+ }
26
+ return (rules.allow || []).some(
27
+ (rule) => rule && (rule.surface === "*" || rule.surface === surface)
28
+ );
29
+ }
30
+
31
+ function messagesOf(body) {
32
+ if (!body || typeof body !== "object") {
33
+ return [];
34
+ }
35
+ return Array.isArray(body) ? body : [body];
36
+ }
37
+
38
+ /**
39
+ * Scopes this channel-MCP body still needs.
40
+ * `scopeHeader` is the WWW-Authenticate scope value when the call is refused.
41
+ * An empty `missing` means the token may proceed.
42
+ */
43
+ function missingChannelScopes(scope, body, catalog) {
44
+ const messages = messagesOf(body);
45
+ const need = new Set();
46
+ for (const msg of messages) {
47
+ if (!msg || typeof msg !== "object") {
48
+ continue;
49
+ }
50
+ const method = msg.method;
51
+ if (!method || String(method).startsWith("notifications/")) {
52
+ continue;
53
+ }
54
+ if (method === "initialize" || method === "ping") {
55
+ continue;
56
+ }
57
+ if (method === "tools/call") {
58
+ const name = msg.params && msg.params.name;
59
+ const entry = (catalog || []).find((tool) => tool.name === name);
60
+ need.add(entry && entry.kind === "event" ? ACT : READ);
61
+ continue;
62
+ }
63
+ need.add(READ);
64
+ }
65
+ return missingFrom(scope, need);
66
+ }
67
+
68
+ const SUBTREE_TOOL_SCOPE = {
69
+ pico_tree: READ,
70
+ pico_channels: READ,
71
+ query: READ,
72
+ raise_event: ACT,
73
+ };
74
+
75
+ function missingSubtreeScopes(scope, body) {
76
+ const messages = messagesOf(body);
77
+ const need = new Set();
78
+ for (const msg of messages) {
79
+ if (!msg || typeof msg !== "object") {
80
+ continue;
81
+ }
82
+ const method = msg.method;
83
+ if (!method || String(method).startsWith("notifications/")) {
84
+ continue;
85
+ }
86
+ if (method === "initialize" || method === "ping") {
87
+ continue;
88
+ }
89
+ if (method === "tools/call") {
90
+ const name = msg.params && msg.params.name;
91
+ need.add(SUBTREE_TOOL_SCOPE[name] || READ);
92
+ continue;
93
+ }
94
+ need.add(READ);
95
+ }
96
+ return missingFrom(scope, need);
97
+ }
98
+
99
+ function missingFrom(scope, need) {
100
+ const missing = [];
101
+ for (const name of need) {
102
+ if (!has(scope, name)) {
103
+ missing.push(name);
104
+ }
105
+ }
106
+ if (missing.length === 0 && !hasOperational(scope)) {
107
+ return { missing: [READ, ACT], scopeHeader: `${READ} ${ACT}` };
108
+ }
109
+ return { missing, scopeHeader: missing.join(" ") };
110
+ }
111
+
112
+ module.exports = {
113
+ READ,
114
+ ACT,
115
+ mcpSurfaceAllowed,
116
+ missingChannelScopes,
117
+ missingSubtreeScopes,
118
+ };
package/mcp/meshHttp.js CHANGED
@@ -5,12 +5,20 @@ const { McpServer } = require("@modelcontextprotocol/sdk/server/mcp.js");
5
5
  const {
6
6
  StreamableHTTPServerTransport,
7
7
  } = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
8
- const { registerMeshTools } = require("./meshTools");
8
+ const { registerMeshTools, meshToolCatalog, getChannelSchema } = require("./meshTools");
9
+ const { registerSubtreeTools } = require("./subtreeTools");
10
+ const {
11
+ mcpSurfaceAllowed,
12
+ missingChannelScopes,
13
+ missingSubtreeScopes,
14
+ } = require("./mcpScopes");
9
15
 
10
16
  const engineVersion = require("../package.json").version;
11
17
 
12
18
  /** @type {Map<string, { transport: import("@modelcontextprotocol/sdk/server/streamableHttp.js").StreamableHTTPServerTransport, mcpServer: import("@modelcontextprotocol/sdk/server/mcp.js").McpServer, eci: string }>} */
13
19
  const sessions = new Map();
20
+ /** @type {typeof sessions} */
21
+ const subtreeSessions = new Map();
14
22
 
15
23
  function bodyHasInitialize(body) {
16
24
  if (!body || typeof body !== "object") return false;
@@ -28,26 +36,22 @@ function sessionIdFromRequest(req) {
28
36
  return typeof raw === "string" && raw.trim() ? raw.trim() : undefined;
29
37
  }
30
38
 
31
- async function createMeshSession(core, eci) {
39
+ async function createSession(sessionMap, name, eci, register) {
32
40
  const mcpServer = new McpServer(
33
- {
34
- name: "pico-engine-mesh",
35
- version: engineVersion,
36
- },
41
+ { name, version: engineVersion },
37
42
  { capabilities: { tools: {}, resources: {} } }
38
43
  );
39
-
40
- registerMeshTools(mcpServer, core, eci);
44
+ register(mcpServer);
41
45
 
42
46
  const transport = new StreamableHTTPServerTransport({
43
47
  sessionIdGenerator: () => randomUUID(),
44
48
  onsessioninitialized: (sessionId) => {
45
- sessions.set(sessionId, { transport, mcpServer, eci });
49
+ sessionMap.set(sessionId, { transport, mcpServer, eci });
46
50
  },
47
51
  onsessionclosed: async (sessionId) => {
48
- const row = sessions.get(sessionId);
52
+ const row = sessionMap.get(sessionId);
49
53
  if (row) {
50
- sessions.delete(sessionId);
54
+ sessionMap.delete(sessionId);
51
55
  try {
52
56
  await row.mcpServer.close();
53
57
  } catch (_e) {
@@ -63,13 +67,43 @@ async function createMeshSession(core, eci) {
63
67
 
64
68
  /**
65
69
  * Streamable HTTP mesh MCP at `/mcp/:eci` (OAuth bearer scoped to that ECI).
70
+ *
71
+ * `wwwAuthenticate(eci, error)` builds the RFC 6750 challenge. `error` is
72
+ * omitted when the client sent no token.
66
73
  */
67
- function registerMeshMcpRoutes(app, core, oauth) {
74
+ function registerMeshMcpRoutes(app, core, oauth, wwwAuthenticate) {
68
75
  if (!oauth) {
69
76
  return;
70
77
  }
71
78
 
72
- async function requireMeshBearer(req, res, next) {
79
+ function challenge(req, res, eci, surface, error, scope) {
80
+ if (typeof wwwAuthenticate === "function") {
81
+ res.set("WWW-Authenticate", wwwAuthenticate(eci, error, req, surface, scope));
82
+ res.set("Access-Control-Expose-Headers", "WWW-Authenticate");
83
+ }
84
+ }
85
+
86
+ function unauthorized(req, res, eci, surface, error) {
87
+ challenge(req, res, eci, surface, error);
88
+ res.status(401).json({
89
+ error: error === "invalid_token" ? "Invalid or expired token" : "Bearer token required",
90
+ });
91
+ }
92
+
93
+ function insufficientScope(req, res, eci, surface, scopeHeader) {
94
+ challenge(req, res, eci, surface, "insufficient_scope", scopeHeader);
95
+ res.status(403).json({ error: "insufficient_scope", scope: scopeHeader });
96
+ }
97
+
98
+ function bearerToken(req) {
99
+ const header = req.headers.authorization;
100
+ if (typeof header !== "string" || !header.startsWith("Bearer ")) {
101
+ return null;
102
+ }
103
+ return header.slice("Bearer ".length).trim();
104
+ }
105
+
106
+ async function requireChannelBearer(req, res, next) {
73
107
  const eci = req.params.eci;
74
108
  if (!eci) {
75
109
  res.status(400).json({ error: "Missing channel ECI" });
@@ -81,57 +115,129 @@ function registerMeshMcpRoutes(app, core, oauth) {
81
115
  res.status(404).json({ error: "Unknown channel ECI" });
82
116
  return;
83
117
  }
84
- const header = req.headers.authorization;
85
- if (typeof header !== "string" || !header.startsWith("Bearer ")) {
86
- res.status(401).json({ error: "Bearer token required" });
118
+ const token = bearerToken(req);
119
+ if (!token) {
120
+ unauthorized(req, res, eci, "channel");
87
121
  return;
88
122
  }
89
- const token = header.slice("Bearer ".length).trim();
90
123
  try {
91
- const valid = await oauth.validateSkyBearerToken(token, eci);
92
- if (!valid) {
93
- res.status(401).json({ error: "Invalid or expired token" });
124
+ const auth = await oauth.resolveMcpChannelToken(token, eci);
125
+ if (!auth) {
126
+ unauthorized(req, res, eci, "channel", "invalid_token");
127
+ return;
128
+ }
129
+ const catalog = meshToolCatalog(getChannelSchema(core, eci));
130
+ const decision = missingChannelScopes(auth.scope, req.body, catalog);
131
+ if (decision.missing.length) {
132
+ insufficientScope(req, res, eci, "channel", decision.scopeHeader);
94
133
  return;
95
134
  }
135
+ const channel = core.picoFramework.lookupChannel(eci);
136
+ if (!mcpSurfaceAllowed(channel.mcpPolicy, "channel")) {
137
+ res.status(403).json({ error: "Channel is not exposed to MCP" });
138
+ return;
139
+ }
140
+ req.mcpAuth = auth;
96
141
  next();
97
142
  } catch (err) {
98
143
  next(err);
99
144
  }
100
145
  }
101
146
 
102
- const handler = async (req, res, next) => {
147
+ async function requireSubtreeBearer(req, res, next) {
148
+ const eci = req.params.eci;
149
+ if (!eci) {
150
+ res.status(400).json({ error: "Missing channel ECI" });
151
+ return;
152
+ }
103
153
  try {
104
- const eci = req.params.eci;
105
- const sessionId = sessionIdFromRequest(req);
106
- let row = sessionId ? sessions.get(sessionId) : undefined;
107
-
108
- if (!row && req.method === "POST" && bodyHasInitialize(req.body)) {
109
- row = await createMeshSession(core, eci);
110
- }
111
-
112
- if (!row) {
113
- if (sessionId) {
114
- res.status(404).json({ error: "Unknown MCP session" });
115
- return;
116
- }
117
- res.status(400).json({
118
- error: "MCP session required (send initialize on POST without session id)",
119
- });
154
+ core.picoFramework.lookupChannel(eci);
155
+ } catch (_e) {
156
+ res.status(404).json({ error: "Unknown channel ECI" });
157
+ return;
158
+ }
159
+ const token = bearerToken(req);
160
+ if (!token) {
161
+ unauthorized(req, res, eci, "mesh");
162
+ return;
163
+ }
164
+ try {
165
+ const auth = await oauth.resolveMcpMeshToken(token, eci);
166
+ if (!auth) {
167
+ unauthorized(req, res, eci, "mesh", "invalid_token");
120
168
  return;
121
169
  }
122
-
123
- if (row.eci !== eci) {
124
- res.status(403).json({ error: "Session ECI mismatch" });
170
+ const decision = missingSubtreeScopes(auth.scope, req.body);
171
+ if (decision.missing.length) {
172
+ insufficientScope(req, res, eci, "mesh", decision.scopeHeader);
125
173
  return;
126
174
  }
127
-
128
- await row.transport.handleRequest(req, res, req.body);
175
+ req.mcpAuth = auth;
176
+ next();
129
177
  } catch (err) {
130
178
  next(err);
131
179
  }
132
- };
180
+ }
181
+
182
+ function sessionHandler(sessionMap, create) {
183
+ return async (req, res, next) => {
184
+ try {
185
+ const eci = req.params.eci;
186
+ const sessionId = sessionIdFromRequest(req);
187
+ let row = sessionId ? sessionMap.get(sessionId) : undefined;
133
188
 
134
- app.all("/mcp/:eci", requireMeshBearer, handler);
189
+ if (!row && req.method === "POST" && bodyHasInitialize(req.body)) {
190
+ row = await create(eci, req.mcpAuth);
191
+ }
192
+
193
+ if (!row) {
194
+ if (sessionId) {
195
+ res.status(404).json({ error: "Unknown MCP session" });
196
+ return;
197
+ }
198
+ res.status(400).json({
199
+ error: "MCP session required (send initialize on POST without session id)",
200
+ });
201
+ return;
202
+ }
203
+
204
+ if (row.eci !== eci) {
205
+ res.status(403).json({ error: "Session ECI mismatch" });
206
+ return;
207
+ }
208
+
209
+ await row.transport.handleRequest(req, res, req.body);
210
+ } catch (err) {
211
+ next(err);
212
+ }
213
+ };
214
+ }
215
+
216
+ app.all(
217
+ "/mcp/mesh/:eci",
218
+ requireSubtreeBearer,
219
+ sessionHandler(subtreeSessions, (eci, auth) =>
220
+ createSession(subtreeSessions, "pico-engine-subtree", eci, (mcpServer) => {
221
+ registerSubtreeTools(mcpServer, core, auth.rootPicoId);
222
+ })
223
+ )
224
+ );
225
+
226
+ app.all(
227
+ "/mcp/:eci",
228
+ requireChannelBearer,
229
+ sessionHandler(sessions, (eci) =>
230
+ createSession(sessions, "pico-engine-mesh", eci, (mcpServer) => {
231
+ registerMeshTools(mcpServer, core, eci);
232
+ })
233
+ )
234
+ );
135
235
  }
136
236
 
137
- module.exports = { registerMeshMcpRoutes, sessions, meshToolCatalog: require("./meshTools").meshToolCatalog, getChannelSchema: require("./meshTools").getChannelSchema };
237
+ module.exports = {
238
+ registerMeshMcpRoutes,
239
+ sessions,
240
+ subtreeSessions,
241
+ meshToolCatalog: require("./meshTools").meshToolCatalog,
242
+ getChannelSchema: require("./meshTools").getChannelSchema,
243
+ };
package/mcp/runStdio.js CHANGED
@@ -7,6 +7,7 @@ const {
7
7
  const { EngineClient } = require("./engineClient");
8
8
  const { registerDevTools } = require("./devTools");
9
9
  const { registerDevResources } = require("./devResources");
10
+ const { registerTryItTools } = require("./tryItTools");
10
11
 
11
12
  async function runDevMcpStdio() {
12
13
  const client = new EngineClient();
@@ -25,6 +26,7 @@ async function runDevMcpStdio() {
25
26
  );
26
27
 
27
28
  registerDevTools(server, client);
29
+ registerTryItTools(server, client);
28
30
  registerDevResources(server, client);
29
31
 
30
32
  const transport = new StdioServerTransport();
@@ -0,0 +1,184 @@
1
+ "use strict";
2
+
3
+ const { z } = require("zod");
4
+ const { mcpSurfaceAllowed } = require("./mcpScopes");
5
+ const { getChannelSchema } = require("./meshTools");
6
+
7
+ function jsonText(data) {
8
+ return JSON.stringify(data, null, 2);
9
+ }
10
+
11
+ function textResult(text, isError = false) {
12
+ return {
13
+ content: [{ type: "text", text }],
14
+ isError,
15
+ };
16
+ }
17
+
18
+ function errorResult(message) {
19
+ return textResult(jsonText({ error: message }), true);
20
+ }
21
+
22
+ function picoInSubtree(pf, picoId, rootPicoId) {
23
+ try {
24
+ let pico = pf.getPico(picoId);
25
+ while (pico) {
26
+ if (pico.id === rootPicoId) {
27
+ return true;
28
+ }
29
+ if (!pico.parent) {
30
+ return false;
31
+ }
32
+ pico = pf.getPico(pico.parent);
33
+ }
34
+ } catch (_e) {
35
+ return false;
36
+ }
37
+ return false;
38
+ }
39
+
40
+ async function picoTree(pf, picoId) {
41
+ const pico = pf.getPico(picoId);
42
+ const readOnly = pico.toReadOnly();
43
+ let name = null;
44
+ try {
45
+ const stored = await pico.getEnt("io.picolabs.wrangler", "name");
46
+ name = stored == null || stored === "" ? null : stored;
47
+ } catch (_e) {
48
+ name = null;
49
+ }
50
+ const children = [];
51
+ for (const childId of readOnly.children || []) {
52
+ children.push(await picoTree(pf, childId));
53
+ }
54
+ return {
55
+ id: readOnly.id,
56
+ name,
57
+ rulesets: (readOnly.rulesets || []).map((ruleset) => ruleset.rid),
58
+ children,
59
+ };
60
+ }
61
+
62
+ function meshChannels(core, picoId) {
63
+ const pico = core.picoFramework.getPico(picoId);
64
+ const channels = [];
65
+ for (const channel of Object.values(pico.channels || {})) {
66
+ const readOnly = channel.toReadOnly ? channel.toReadOnly() : channel;
67
+ if (!mcpSurfaceAllowed(readOnly.mcpPolicy, "mesh")) {
68
+ continue;
69
+ }
70
+ channels.push({
71
+ id: readOnly.id,
72
+ tags: readOnly.tags || [],
73
+ channelSchema: getChannelSchema(core, readOnly.id),
74
+ });
75
+ }
76
+ return channels;
77
+ }
78
+
79
+ function registerSubtreeTools(server, core, rootPicoId) {
80
+ const pf = core.picoFramework;
81
+
82
+ server.tool(
83
+ "pico_tree",
84
+ "Children, names, and installed rulesets for this mesh",
85
+ {},
86
+ async () => textResult(jsonText(await picoTree(pf, rootPicoId)))
87
+ );
88
+
89
+ server.tool(
90
+ "pico_channels",
91
+ "Channels exposed to this mesh endpoint, with tags and channelSchema",
92
+ { pico: z.string() },
93
+ async ({ pico }) => {
94
+ if (!picoInSubtree(pf, pico, rootPicoId)) {
95
+ return errorResult("Pico is not in this mesh");
96
+ }
97
+ return textResult(jsonText(meshChannels(core, pico)));
98
+ }
99
+ );
100
+
101
+ server.tool(
102
+ "query",
103
+ "Run a query on a channel exposed to this mesh endpoint",
104
+ {
105
+ eci: z.string(),
106
+ rid: z.string(),
107
+ name: z.string(),
108
+ args: z.record(z.any()).optional(),
109
+ },
110
+ async ({ eci, rid, name, args }) => {
111
+ const refused = refuseChannel(pf, eci, rootPicoId);
112
+ if (refused) {
113
+ return refused;
114
+ }
115
+ try {
116
+ const data = await core.query({
117
+ eci,
118
+ rid,
119
+ name,
120
+ args: args || {},
121
+ });
122
+ return textResult(jsonText(data));
123
+ } catch (err) {
124
+ return policyOrError(err);
125
+ }
126
+ }
127
+ );
128
+
129
+ server.tool(
130
+ "raise_event",
131
+ "Raise an event on a channel exposed to this mesh endpoint",
132
+ {
133
+ eci: z.string(),
134
+ domain: z.string(),
135
+ type: z.string(),
136
+ attrs: z.record(z.any()).optional(),
137
+ },
138
+ async ({ eci, domain, type, attrs }) => {
139
+ const refused = refuseChannel(pf, eci, rootPicoId);
140
+ if (refused) {
141
+ return refused;
142
+ }
143
+ try {
144
+ const data = await core.eventWait({
145
+ eci,
146
+ domain,
147
+ name: type,
148
+ data: { attrs: attrs || {} },
149
+ time: 0,
150
+ });
151
+ return textResult(jsonText(data));
152
+ } catch (err) {
153
+ return policyOrError(err);
154
+ }
155
+ }
156
+ );
157
+ }
158
+
159
+ function refuseChannel(pf, eci, rootPicoId) {
160
+ let channel;
161
+ try {
162
+ channel = pf.lookupChannel(eci);
163
+ } catch (_e) {
164
+ return errorResult("Unknown channel");
165
+ }
166
+ if (!picoInSubtree(pf, channel.pico.id, rootPicoId)) {
167
+ return errorResult("Channel is not in this mesh");
168
+ }
169
+ const readOnly = channel.toReadOnly();
170
+ if (!mcpSurfaceAllowed(readOnly.mcpPolicy, "mesh")) {
171
+ return errorResult("Channel is not exposed to the mesh endpoint");
172
+ }
173
+ return null;
174
+ }
175
+
176
+ function policyOrError(err) {
177
+ const msg = String((err && err.message) || err);
178
+ const policy =
179
+ /policy|not allowed|denied|forbidden/i.test(msg) ||
180
+ /channel.*(event|query)/i.test(msg);
181
+ return textResult(jsonText({ error: msg, kind: policy ? "policy" : "error" }), true);
182
+ }
183
+
184
+ module.exports = { registerSubtreeTools };