@lunora/mcp 1.0.0-alpha.229 → 1.0.0-alpha.230

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.
package/dist/bin.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{parseAgentsEnv as N}from"./packem_shared/AGENT_RUN_INPUT_SCHEMA-hKbpa3Dg.mjs";import{connectStdio as l}from"./packem_shared/connectStdio-Cpwf1Lbw.mjs";const E=new Set(["1","on","true","yes"]),o=r=>r!==void 0&&E.has(r.trim().toLowerCase());class s extends Error{code;constructor(e,a){super(e),this.name="BinError",this.code=a}}const O=async(r,e={})=>{const a=e.connect??l,i=e.writeError??(t=>{process.stderr.write(t)}),n=r.LUNORA_URL;if(n===void 0||n.length===0)throw i(`lunora-mcp: LUNORA_URL environment variable is required
2
+ import{parseAgentsEnv as N}from"./packem_shared/AGENT_RUN_INPUT_SCHEMA-hKbpa3Dg.mjs";import{connectStdio as l}from"./packem_shared/connectStdio-n-RHjcwN.mjs";const E=new Set(["1","on","true","yes"]),o=r=>r!==void 0&&E.has(r.trim().toLowerCase());class s extends Error{code;constructor(e,a){super(e),this.name="BinError",this.code=a}}const O=async(r,e={})=>{const a=e.connect??l,i=e.writeError??(t=>{process.stderr.write(t)}),n=r.LUNORA_URL;if(n===void 0||n.length===0)throw i(`lunora-mcp: LUNORA_URL environment variable is required
3
3
  `),new s("LUNORA_URL environment variable is required",1);const c=r.LUNORA_ADMIN_TOKEN;if(c===void 0||c.length===0)throw i(`lunora-mcp: LUNORA_ADMIN_TOKEN environment variable is required (every tool reads admin-gated routes)
4
4
  `),new s("LUNORA_ADMIN_TOKEN environment variable is required",1);const A=Number(r.LUNORA_MCP_AGENT_TIMEOUT_MS),_=Number.isFinite(A)&&A>0?A:void 0;try{await a({agents:N(r.LUNORA_MCP_AGENTS),allowAgents:o(r.LUNORA_MCP_ALLOW_AGENTS),allowDataReads:o(r.LUNORA_MCP_ALLOW_DATA_READS),allowObservability:o(r.LUNORA_MCP_ALLOW_OBSERVABILITY),allowWrites:o(r.LUNORA_MCP_ALLOW_WRITES),token:c,url:n,..._===void 0?{}:{agentMaxWaitMs:_}})}catch(t){const L=t instanceof Error?t.message:String(t);throw i(`lunora-mcp: failed to start — ${L}
5
5
  `),new s(`failed to start — ${L}`,1)}};try{await O(process.env)}catch(r){process.exit(r instanceof s?r.code:1)}
package/dist/index.d.mts CHANGED
@@ -108,6 +108,14 @@ interface LunoraMcpServerOptions {
108
108
  * opted in. Only takes effect together with a non-empty `agents` list.
109
109
  */
110
110
  allowAgents?: boolean;
111
+ /**
112
+ * Expose `lunora_find_related`, which returns raw table rows read through the
113
+ * admin writer, so RLS policies and column masks do not apply. Defaults to
114
+ * `false`, for the same reason as `allowObservability`. Only takes effect
115
+ * when a `token` resolved. On the OAuth-protected path the verified token must
116
+ * also carry the data-read scope (see `DATA_READ_SCOPE` in `./tools`).
117
+ */
118
+ allowDataReads?: boolean;
111
119
  /**
112
120
  * Expose the observability tools (`lunora_get_logs`, `lunora_get_issues`,
113
121
  * `lunora_get_advisories`, `lunora_get_query_insights`,
@@ -117,9 +125,10 @@ interface LunoraMcpServerOptions {
117
125
  * lands in the model's context and therefore at its provider. Holding the
118
126
  * admin bearer is not consent to ship that, so it is a separate opt-in;
119
127
  * without it the tools are omitted from the advertised list AND refused at
120
- * dispatch. Only takes effect when a `token` resolved.
128
+ * dispatch. Only takes effect when a `token` resolved. On the OAuth-protected
129
+ * path the verified token must also carry the observability scope (see
130
+ * `OBSERVABILITY_SCOPE` in `./tools`); this option stays the outer gate.
121
131
  */
122
- allowDataReads?: boolean;
123
132
  allowObservability?: boolean;
124
133
  /**
125
134
  * Expose the write tools (`lunora_run_mutation` / `lunora_run_action`).
@@ -234,7 +243,9 @@ interface AuthedMcpFetchHandlerOptions {
234
243
  * side effect). A token without `scope` still sees them in `tools/list`, and
235
244
  * a `tools/call` to one throws `challenge([scope])` instead of running, so the
236
245
  * client can re-authorize for the scope and retry. Unset, tools follow
237
- * `allowWrites` / `allowAgents` alone.
246
+ * `allowWrites` / `allowAgents` alone. The raw-row and observability families
247
+ * need their own token scopes with or without `stepUp`; without it a call
248
+ * without the scope is refused as a tool error, not challenged.
238
249
  */
239
250
  stepUp?: {
240
251
  /**
package/dist/index.d.ts CHANGED
@@ -108,6 +108,14 @@ interface LunoraMcpServerOptions {
108
108
  * opted in. Only takes effect together with a non-empty `agents` list.
109
109
  */
110
110
  allowAgents?: boolean;
111
+ /**
112
+ * Expose `lunora_find_related`, which returns raw table rows read through the
113
+ * admin writer, so RLS policies and column masks do not apply. Defaults to
114
+ * `false`, for the same reason as `allowObservability`. Only takes effect
115
+ * when a `token` resolved. On the OAuth-protected path the verified token must
116
+ * also carry the data-read scope (see `DATA_READ_SCOPE` in `./tools`).
117
+ */
118
+ allowDataReads?: boolean;
111
119
  /**
112
120
  * Expose the observability tools (`lunora_get_logs`, `lunora_get_issues`,
113
121
  * `lunora_get_advisories`, `lunora_get_query_insights`,
@@ -117,9 +125,10 @@ interface LunoraMcpServerOptions {
117
125
  * lands in the model's context and therefore at its provider. Holding the
118
126
  * admin bearer is not consent to ship that, so it is a separate opt-in;
119
127
  * without it the tools are omitted from the advertised list AND refused at
120
- * dispatch. Only takes effect when a `token` resolved.
128
+ * dispatch. Only takes effect when a `token` resolved. On the OAuth-protected
129
+ * path the verified token must also carry the observability scope (see
130
+ * `OBSERVABILITY_SCOPE` in `./tools`); this option stays the outer gate.
121
131
  */
122
- allowDataReads?: boolean;
123
132
  allowObservability?: boolean;
124
133
  /**
125
134
  * Expose the write tools (`lunora_run_mutation` / `lunora_run_action`).
@@ -234,7 +243,9 @@ interface AuthedMcpFetchHandlerOptions {
234
243
  * side effect). A token without `scope` still sees them in `tools/list`, and
235
244
  * a `tools/call` to one throws `challenge([scope])` instead of running, so the
236
245
  * client can re-authorize for the scope and retry. Unset, tools follow
237
- * `allowWrites` / `allowAgents` alone.
246
+ * `allowWrites` / `allowAgents` alone. The raw-row and observability families
247
+ * need their own token scopes with or without `stepUp`; without it a call
248
+ * without the scope is refused as a tool error, not challenged.
238
249
  */
239
250
  stepUp?: {
240
251
  /**
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{AGENT_RUN_INPUT_SCHEMA as r,AGENT_STATUS_TOOL_NAME as t,agentToolDefinitions as c,callAgentTool as T,parseAgentsEnv as a}from"./packem_shared/AGENT_RUN_INPUT_SCHEMA-hKbpa3Dg.mjs";import{createAuthedMcpFetchHandler as S,mcpTokenScopes as _}from"./packem_shared/createAuthedMcpFetchHandler-o5r1AXH-.mjs";import{createToolServer as l}from"./packem_shared/createToolServer-BtGuPyMU.mjs";import{createMcpFetchHandler as n}from"./packem_shared/createMcpFetchHandler-B8mrSCqy.mjs";import{LOCAL_SERVER_NAME as N,NO_DEPLOYMENT_MESSAGE as s,connectLocalStdio as I,createLocalMcpServer as L,localTools as f}from"./packem_shared/LOCAL_SERVER_NAME-C0IDD-qv.mjs";import{createPaidMcpServer as M}from"./packem_shared/createPaidMcpServer-C_V1beyQ.mjs";import{connectStdio as i,createLunoraMcpServer as D}from"./packem_shared/connectStdio-Cpwf1Lbw.mjs";import{R as d,W as v,c as F,t as U}from"./packem_shared/tools-CFdbSZHO.mjs";import{DEFAULT_MAX_REQUEST_BYTES as g,serveStateless as h}from"./packem_shared/DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{O as G}from"./packem_shared/observability-tools-D4Z8dGS-.mjs";export{r as AGENT_RUN_INPUT_SCHEMA,t as AGENT_STATUS_TOOL_NAME,g as DEFAULT_MAX_REQUEST_BYTES,N as LOCAL_SERVER_NAME,s as NO_DEPLOYMENT_MESSAGE,G as OBSERVABILITY_TOOL_DEFINITIONS,d as READ_ONLY_TOOL_DEFINITIONS,v as WRITE_TOOL_DEFINITIONS,c as agentToolDefinitions,T as callAgentTool,F as callTool,I as connectLocalStdio,i as connectStdio,S as createAuthedMcpFetchHandler,L as createLocalMcpServer,D as createLunoraMcpServer,n as createMcpFetchHandler,M as createPaidMcpServer,l as createToolServer,f as localTools,_ as mcpTokenScopes,a as parseAgentsEnv,h as serveStateless,U as toolDefinitions};
1
+ import{AGENT_RUN_INPUT_SCHEMA as r,AGENT_STATUS_TOOL_NAME as t,agentToolDefinitions as c,callAgentTool as T,parseAgentsEnv as a}from"./packem_shared/AGENT_RUN_INPUT_SCHEMA-hKbpa3Dg.mjs";import{createAuthedMcpFetchHandler as S,mcpTokenScopes as _}from"./packem_shared/createAuthedMcpFetchHandler-DUHhAwgo.mjs";import{createToolServer as l}from"./packem_shared/createToolServer-BtGuPyMU.mjs";import{createMcpFetchHandler as n}from"./packem_shared/createMcpFetchHandler-CNEfLA-N.mjs";import{LOCAL_SERVER_NAME as N,NO_DEPLOYMENT_MESSAGE as s,connectLocalStdio as I,createLocalMcpServer as L,localTools as f}from"./packem_shared/LOCAL_SERVER_NAME-DM_NJ-eY.mjs";import{createPaidMcpServer as M}from"./packem_shared/createPaidMcpServer-C_V1beyQ.mjs";import{connectStdio as i,createLunoraMcpServer as D}from"./packem_shared/connectStdio-n-RHjcwN.mjs";import{R as d,W as v,c as F,t as U}from"./packem_shared/tools-Dmnb3M2T.mjs";import{DEFAULT_MAX_REQUEST_BYTES as g,serveStateless as h}from"./packem_shared/DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{O as G}from"./packem_shared/observability-tools-D4Z8dGS-.mjs";export{r as AGENT_RUN_INPUT_SCHEMA,t as AGENT_STATUS_TOOL_NAME,g as DEFAULT_MAX_REQUEST_BYTES,N as LOCAL_SERVER_NAME,s as NO_DEPLOYMENT_MESSAGE,G as OBSERVABILITY_TOOL_DEFINITIONS,d as READ_ONLY_TOOL_DEFINITIONS,v as WRITE_TOOL_DEFINITIONS,c as agentToolDefinitions,T as callAgentTool,F as callTool,I as connectLocalStdio,i as connectStdio,S as createAuthedMcpFetchHandler,L as createLocalMcpServer,D as createLunoraMcpServer,n as createMcpFetchHandler,M as createPaidMcpServer,l as createToolServer,f as localTools,_ as mcpTokenScopes,a as parseAgentsEnv,h as serveStateless,U as toolDefinitions};
@@ -1 +1 @@
1
- import{LunoraClient as f}from"@lunora/client";import{StdioServerTransport as m}from"@modelcontextprotocol/sdk/server/stdio.js";import{e as p}from"./promise-memo-OqVPWoUX.mjs";import{createToolServer as v}from"./createToolServer-BtGuPyMU.mjs";import{createRemoteDocsIndex as h}from"./DEFAULT_DOCS_BASE_URL-CiHy_Dbz.mjs";import{docsResources as E}from"./DOCS_URI_SCHEME-C35UQ5Fo.mjs";import{docsTools as y}from"./DEFAULT_SEARCH_LIMIT-B8C5JM2y.mjs";import{E as R,b as O,t as T,d as _,c as S}from"./tools-CFdbSZHO.mjs";const l=e=>e.docs===!1?void 0:h({...e.docs?.baseUrl===void 0?{}:{baseUrl:e.docs.baseUrl},...e.fetch===void 0?{}:{fetch:e.fetch}}),P="lunora",C="no Lunora dev server is running for this project — start one with `lunora dev`, then call this tool again (call lunora_dev_status to check).",g=8,d=e=>{const n=new Map;return t=>{const r=JSON.stringify([t.url,t.token??""]),c=n.get(r);if(c!==void 0)return c;const o=new f({fetch:e,url:t.url});return t.token!==void 0&&t.token.length>0&&o.setAuthToken(t.token),p(n,g),n.set(r,o),o}},i=e=>e?.token!==void 0&&e.token.length>0,A=(e,n,t)=>{const r=typeof e=="function"?e:()=>e;return T(n,i(r())).filter(c=>!_.has(c.name)).map(c=>({definition:c,handle:async o=>{const s=r();return s===void 0?{content:[{text:C,type:"text"}],isError:!0}:S(t(s),c.name,o,n,i(s))}}))},I=()=>R.map(e=>({definition:e,handle:n=>Promise.resolve(O(e.name,n))})),N="lunora-spec:openrpc",k="lunora-spec:openapi",a=[{description:"The deployment's generated OpenRPC 1.x document — every RPC function's path, kind, and argument schema in one read, instead of list_functions plus one get_function_schema call per function.",fetch:async e=>e.fetchOpenRpc(),name:"OpenRPC specification",uri:N},{description:"The deployment's generated OpenAPI 3.1 document.",fetch:async e=>e.fetchOpenApi(),name:"OpenAPI specification",uri:k}],w=(e,n)=>{const t=typeof e=="function"?e:()=>e,r=async c=>{const o=t();if(o!==void 0)try{return await c.fetch(n(o))}catch{return}};return{list:async()=>(await Promise.all(a.map(async o=>await r(o)===void 0?void 0:{description:o.description,mimeType:"application/json",name:o.name,uri:o.uri}))).filter(o=>o!==void 0),read:async c=>{const o=a.find(u=>u.uri===c);if(o===void 0)return;const s=await r(o);return s===void 0?void 0:{mimeType:"application/json",text:JSON.stringify(s,void 0,2)}}}},x=e=>({list:async()=>(await Promise.all(e.map(async t=>t.list()))).flat(),read:async n=>{for(const t of e){const r=await t.read(n);if(r!==void 0)return r}}}),L=(e,n)=>{const t=[],r=l(e);return r!==void 0&&t.push(...y(r)),t.push(...e.extraTools??[],...I()),e.deployment!==void 0&&t.push(...A(e.deployment,e.allowWrites??!1,n??d(e.fetch))),t},U=(e={})=>{const n=l(e),t=[];n!==void 0&&t.push(E(n));const r=d(e.fetch);return e.deployment!==void 0&&t.push(w(e.deployment,r)),v({name:P,version:e.version??"0.0.0"},L(e,r),t.length===0?void 0:x(t))},H=async(e={})=>{const n=U(e);return await n.connect(new m),n};export{P as LOCAL_SERVER_NAME,C as NO_DEPLOYMENT_MESSAGE,k as OPENAPI_RESOURCE_URI,N as OPENRPC_RESOURCE_URI,H as connectLocalStdio,U as createLocalMcpServer,L as localTools};
1
+ import{LunoraClient as f}from"@lunora/client";import{StdioServerTransport as m}from"@modelcontextprotocol/sdk/server/stdio.js";import{e as p}from"./promise-memo-OqVPWoUX.mjs";import{createToolServer as v}from"./createToolServer-BtGuPyMU.mjs";import{createRemoteDocsIndex as h}from"./DEFAULT_DOCS_BASE_URL-CiHy_Dbz.mjs";import{docsResources as E}from"./DOCS_URI_SCHEME-C35UQ5Fo.mjs";import{docsTools as y}from"./DEFAULT_SEARCH_LIMIT-B8C5JM2y.mjs";import{E as R,b as O,t as T,d as _,c as S}from"./tools-Dmnb3M2T.mjs";const l=e=>e.docs===!1?void 0:h({...e.docs?.baseUrl===void 0?{}:{baseUrl:e.docs.baseUrl},...e.fetch===void 0?{}:{fetch:e.fetch}}),P="lunora",C="no Lunora dev server is running for this project — start one with `lunora dev`, then call this tool again (call lunora_dev_status to check).",g=8,d=e=>{const n=new Map;return t=>{const r=JSON.stringify([t.url,t.token??""]),c=n.get(r);if(c!==void 0)return c;const o=new f({fetch:e,url:t.url});return t.token!==void 0&&t.token.length>0&&o.setAuthToken(t.token),p(n,g),n.set(r,o),o}},i=e=>e?.token!==void 0&&e.token.length>0,A=(e,n,t)=>{const r=typeof e=="function"?e:()=>e;return T(n,i(r())).filter(c=>!_.has(c.name)).map(c=>({definition:c,handle:async o=>{const s=r();return s===void 0?{content:[{text:C,type:"text"}],isError:!0}:S(t(s),c.name,o,n,i(s))}}))},I=()=>R.map(e=>({definition:e,handle:n=>Promise.resolve(O(e.name,n))})),N="lunora-spec:openrpc",k="lunora-spec:openapi",a=[{description:"The deployment's generated OpenRPC 1.x document — every RPC function's path, kind, and argument schema in one read, instead of list_functions plus one get_function_schema call per function.",fetch:async e=>e.fetchOpenRpc(),name:"OpenRPC specification",uri:N},{description:"The deployment's generated OpenAPI 3.1 document.",fetch:async e=>e.fetchOpenApi(),name:"OpenAPI specification",uri:k}],w=(e,n)=>{const t=typeof e=="function"?e:()=>e,r=async c=>{const o=t();if(o!==void 0)try{return await c.fetch(n(o))}catch{return}};return{list:async()=>(await Promise.all(a.map(async o=>await r(o)===void 0?void 0:{description:o.description,mimeType:"application/json",name:o.name,uri:o.uri}))).filter(o=>o!==void 0),read:async c=>{const o=a.find(u=>u.uri===c);if(o===void 0)return;const s=await r(o);return s===void 0?void 0:{mimeType:"application/json",text:JSON.stringify(s,void 0,2)}}}},x=e=>({list:async()=>(await Promise.all(e.map(async t=>t.list()))).flat(),read:async n=>{for(const t of e){const r=await t.read(n);if(r!==void 0)return r}}}),L=(e,n)=>{const t=[],r=l(e);return r!==void 0&&t.push(...y(r)),t.push(...e.extraTools??[],...I()),e.deployment!==void 0&&t.push(...A(e.deployment,e.allowWrites??!1,n??d(e.fetch))),t},U=(e={})=>{const n=l(e),t=[];n!==void 0&&t.push(E(n));const r=d(e.fetch);return e.deployment!==void 0&&t.push(w(e.deployment,r)),v({name:P,version:e.version??"0.0.0"},L(e,r),t.length===0?void 0:x(t))},H=async(e={})=>{const n=U(e);return await n.connect(new m),n};export{P as LOCAL_SERVER_NAME,C as NO_DEPLOYMENT_MESSAGE,k as OPENAPI_RESOURCE_URI,N as OPENRPC_RESOURCE_URI,H as connectLocalStdio,U as createLocalMcpServer,L as localTools};
@@ -0,0 +1 @@
1
+ import{D as T,O as E,R as _,e as s,S as a,W as o,a as S,c as D,s as N,t as A}from"./tools-Dmnb3M2T.mjs";import{O as L}from"./observability-tools-D4Z8dGS-.mjs";export{T as DATA_READ_SCOPE,E as OBSERVABILITY_SCOPE,L as OBSERVABILITY_TOOL_DEFINITIONS,_ as READ_ONLY_TOOL_DEFINITIONS,s as ROW_READ_TOOL_DEFINITIONS,a as SCOPED_GATES,o as WRITE_TOOL_DEFINITIONS,S as WRITE_TOOL_NAMES,D as callTool,N as scopeForTool,A as toolDefinitions};
@@ -1 +1 @@
1
- import{readFileSync as d}from"node:fs";import{dirname as m,join as w}from"node:path";import{fileURLToPath as h}from"node:url";import{LunoraClient as T}from"@lunora/client";import{LunoraError as f}from"@lunora/errors";import{Server as y}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as A}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as M,CallToolRequestSchema as S}from"@modelcontextprotocol/sdk/types.js";import{agentToolDefinitions as k,isAgentToolName as p,callAgentTool as R}from"./AGENT_RUN_INPUT_SCHEMA-hKbpa3Dg.mjs";import{t as N,c as L}from"./tools-CFdbSZHO.mjs";const E=()=>{try{let e=m(h(import.meta.url));for(let r=0;r<8;r+=1){try{const n=d(w(e,"package.json"),"utf8"),t=JSON.parse(n);if(t.name==="@lunora/mcp"&&typeof t.version=="string"&&t.version.length>0)return t.version}catch{}const a=m(e);if(a===e)break;e=a}}catch{}return"0.0.0"},I={name:"lunora",version:E()},W=e=>{if(e.client!==void 0)return e.client;if(e.url===void 0)throw new f("INTERNAL","createLunoraMcpServer requires either a `client` or a `url`");if(e.token===void 0||e.token.length===0)throw new f("UNAUTHENTICATED","createLunoraMcpServer requires a `token` (LUNORA_ADMIN_TOKEN) alongside `url`: every tool reaches admin-gated /_lunora/admin/* routes, so an unauthenticated server can only 403. Writes stay off unless `allowWrites` is set.");const r=new T({fetch:e.fetch,url:e.url});return r.setAuthToken(e.token),r},b=e=>{const r=W(e),a=e.allowWrites??!1,n=e.allowAgents??!1,t=e.agents??[],s=typeof e.token=="string"&&e.token.length>0,i=e.allowObservability===!0&&s,c=e.allowDataReads===!0&&s,o=new y(I,{capabilities:{tools:{}}});return o.setRequestHandler(M,()=>({tools:[...N(a,i,c),...k(t,n)]})),o.setRequestHandler(S,async v=>{const{arguments:g,name:l}=v.params,u=g??{};return p(l,t)?await R(r,l,u,{allowAgents:n,exposures:t,...e.agentMaxWaitMs===void 0?{}:{maxWaitMs:e.agentMaxWaitMs},...e.agentPollIntervalMs===void 0?{}:{pollIntervalMs:e.agentPollIntervalMs}}):await L(r,l,u,a,i,c)}),o},V=async e=>{const r=b(e);return await r.connect(new A),r};export{V as connectStdio,b as createLunoraMcpServer,W as resolveClient};
1
+ import{readFileSync as d}from"node:fs";import{dirname as m,join as w}from"node:path";import{fileURLToPath as h}from"node:url";import{LunoraClient as T}from"@lunora/client";import{LunoraError as f}from"@lunora/errors";import{Server as y}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as A}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as M,CallToolRequestSchema as S}from"@modelcontextprotocol/sdk/types.js";import{agentToolDefinitions as k,isAgentToolName as p,callAgentTool as R}from"./AGENT_RUN_INPUT_SCHEMA-hKbpa3Dg.mjs";import{t as N,c as L}from"./tools-Dmnb3M2T.mjs";const E=()=>{try{let e=m(h(import.meta.url));for(let r=0;r<8;r+=1){try{const n=d(w(e,"package.json"),"utf8"),t=JSON.parse(n);if(t.name==="@lunora/mcp"&&typeof t.version=="string"&&t.version.length>0)return t.version}catch{}const a=m(e);if(a===e)break;e=a}}catch{}return"0.0.0"},I={name:"lunora",version:E()},W=e=>{if(e.client!==void 0)return e.client;if(e.url===void 0)throw new f("INTERNAL","createLunoraMcpServer requires either a `client` or a `url`");if(e.token===void 0||e.token.length===0)throw new f("UNAUTHENTICATED","createLunoraMcpServer requires a `token` (LUNORA_ADMIN_TOKEN) alongside `url`: every tool reaches admin-gated /_lunora/admin/* routes, so an unauthenticated server can only 403. Writes stay off unless `allowWrites` is set.");const r=new T({fetch:e.fetch,url:e.url});return r.setAuthToken(e.token),r},b=e=>{const r=W(e),a=e.allowWrites??!1,n=e.allowAgents??!1,t=e.agents??[],s=typeof e.token=="string"&&e.token.length>0,i=e.allowObservability===!0&&s,c=e.allowDataReads===!0&&s,o=new y(I,{capabilities:{tools:{}}});return o.setRequestHandler(M,()=>({tools:[...N(a,i,c),...k(t,n)]})),o.setRequestHandler(S,async v=>{const{arguments:g,name:l}=v.params,u=g??{};return p(l,t)?await R(r,l,u,{allowAgents:n,exposures:t,...e.agentMaxWaitMs===void 0?{}:{maxWaitMs:e.agentMaxWaitMs},...e.agentPollIntervalMs===void 0?{}:{pollIntervalMs:e.agentPollIntervalMs}}):await L(r,l,u,a,i,c)}),o},V=async e=>{const r=b(e);return await r.connect(new A),r};export{V as connectStdio,b as createLunoraMcpServer,W as resolveClient};
@@ -0,0 +1 @@
1
+ import{LunoraError as u}from"@lunora/errors";import{isAgentToolName as S}from"./AGENT_RUN_INPUT_SCHEMA-hKbpa3Dg.mjs";import{readScreenedBody as h,serveStateless as g}from"./DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{resolveClient as y,createLunoraMcpServer as v}from"./connectStdio-n-RHjcwN.mjs";import{c as w}from"./tool-call-Bs-QeKp6.mjs";import{S as T,a as A,s as E}from"./tools-Dmnb3M2T.mjs";const M=e=>typeof e.scope!="string"?new Set:new Set(e.scope.split(" ").filter(t=>t!=="")),_=(e,t)=>{const o={...e};for(const{flag:r,scope:n}of T)o[r]=e[r]===!0&&t.has(n);return o},C=(e,t,o)=>{const r=new Set,n=t.agents??[];for(const i of e){const s=w(i);if(s===void 0)continue;(A.has(s)||S(s,n))&&r.add(o);const c=E(s,t);c!==void 0&&r.add(c)}return r},I=e=>{const{maxRequestBytes:t,stepUp:o}=e;if(o!==void 0&&(typeof o.scope!="string"||o.scope===""||typeof o.challenge!="function"))throw new u("MCP_STEP_UP_MISCONFIGURED","createAuthedMcpFetchHandler: `stepUp` needs a non-empty `scope` and a `challenge` function.");const r=typeof e.server=="function"?void 0:y(e.server);return e.protect(async(n,i)=>{const s=M(i),c=typeof e.server=="function"?await e.server(i):{...e.server,client:r},d=_(c,s);let a;if(o!==void 0){const p=await h(n,t);if("response"in p)return p.response;({parsedBody:a}=p);const l=Array.isArray(a)?a:[a],f=[...C(l,c,o.scope)].filter(m=>!s.has(m));if(f.length>0)throw o.challenge(f)}return await g(v(d),n,{maxRequestBytes:t,parsedBody:a})})};export{I as createAuthedMcpFetchHandler,M as mcpTokenScopes};
@@ -1 +1 @@
1
- import{serveStateless as c}from"./DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{DEFAULT_MAX_REQUEST_BYTES as u}from"./DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{resolveClient as s,createLunoraMcpServer as a}from"./connectStdio-Cpwf1Lbw.mjs";const l=e=>{const r=s(e);return t=>c(a({...e,client:r}),t,{maxRequestBytes:e.maxRequestBytes})};export{u as DEFAULT_MAX_REQUEST_BYTES,l as createMcpFetchHandler,c as serveStateless};
1
+ import{serveStateless as c}from"./DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{DEFAULT_MAX_REQUEST_BYTES as u}from"./DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{resolveClient as s,createLunoraMcpServer as a}from"./connectStdio-n-RHjcwN.mjs";const l=e=>{const r=s(e);return t=>c(a({...e,client:r}),t,{maxRequestBytes:e.maxRequestBytes})};export{u as DEFAULT_MAX_REQUEST_BYTES,l as createMcpFetchHandler,c as serveStateless};
@@ -0,0 +1,2 @@
1
+ import{getCatalogEntry as q,resolveHint as Q,findIssueSolution as Y,isInternalCode as D,LunoraError as c}from"@lunora/errors";import{e as l,o as J,a as u,t as G,f as V,b as X,O as z,c as Z}from"./observability-tools-D4Z8dGS-.mjs";import{ADMIN_FUNCTIONS as ee}from"@lunora/shard-engine";import{m as te}from"./promise-memo-OqVPWoUX.mjs";const ne={destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},b="https://lunora.sh/docs/errors",oe={properties:{code:{description:'The error code to explain, e.g. "CONFLICT" or "RLS_REQUIRED". Case-sensitive; codes are SCREAMING_SNAKE_CASE.',type:"string"},message:{description:"The raw error message, when there is no code (codegen and Cloudflare platform errors arrive as plain text). Matched against the solution tables.",type:"string"}},type:"object"},ie={properties:{code:{description:"The code that was looked up, when one was given.",type:"string"},docsUrl:{description:"Link to this code's section of the published error reference.",type:"string"},found:{description:"False when neither the code nor the message matched anything — the other fields are then absent.",type:"boolean"},hint:{description:"Actionable Markdown remediation, when the catalog or a message rule has one.",type:"string"},internal:{description:"True when the code is redacted on the wire: its real message is logged server-side and never reaches a client, so it is absent from the published reference.",type:"boolean"},solution:{description:"A message-matched solution: { id, header, body }, from Lunora's rules or the Cloudflare platform table.",type:"object"},status:{description:"HTTP/RPC status this code maps to on the wire.",type:"number"},title:{description:"Short human-readable summary of the code.",type:"string"}},required:["found"],type:"object"},C=[{annotations:{...ne,title:"Explain a Lunora error"},description:"Explain a Lunora error before guessing at a fix: pass its code (CONFLICT, RLS_REQUIRED, …) or the raw error message, and get the catalog's transport status, title and actionable hint, plus any matched codegen/Cloudflare solution and a link to the reference. Static catalog data — no deployment and no credentials needed.",inputSchema:oe,name:"lunora_explain_error",outputSchema:ie}],re=new Set(C.map(e=>e.name)),E=e=>typeof e=="string"&&e.length>0?e:void 0,se=e=>typeof e=="string"?e:e.join(`
2
+ `),ae=(e,t)=>t?.docsUrl!==void 0?t.docsUrl:e===void 0||t===void 0||D(e)?b:`${b}#${e.toLowerCase()}`,ce=(e,t)=>{const n=e===void 0?void 0:q(e),o=e===void 0?void 0:Q({code:e}),i=t===void 0?void 0:Y(t),r={docsUrl:ae(e,n),found:n!==void 0||i!==void 0};return e!==void 0&&(r.code=e,D(e)&&(r.internal=!0)),n!==void 0&&(r.status=n.status,r.title=n.title),o!==void 0&&(r.hint=se(o)),i!==void 0&&(r.solution={body:i.body,header:i.header,id:i.id}),r},de=(e,t)=>{if(e!=="lunora_explain_error")return l(`unknown error tool: ${e}`);const n=E(t.code),o=E(t.message);return n===void 0&&o===void 0?l('lunora_explain_error needs a "code" or a "message" (or both); received neither.'):J(ce(n,o))},le={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},ue={properties:{cursor:{description:"Opaque cursor from a previous call's continueCursor, to fetch the next page.",type:"string"},depth:{description:"How many hops to follow. 1 (default) is the direct neighbourhood; maximum 4.",type:"number"},direction:{description:'Which way to follow foreign keys: "out" follows the ids this row holds (ticket → customer), "in" the rows that point at it (customer → tickets), "both" (default) does both.',type:"string"},edges:{description:'Restrict the walk to these edge names, each "<table>.<column>" (e.g. "tickets.customerId"). Omit to follow every declared foreign key.',items:{type:"string"},type:"array"},id:{description:"Document id of the row to start from.",type:"string"},limit:{description:"Maximum related rows to return (default 50, maximum 200).",type:"number"},shardKey:{description:"Shard to read from on a .shardBy()-partitioned deployment. Omit for the default (unsharded) shard.",type:"string"},table:{description:'Table the start row lives in, e.g. "customers".',type:"string"}},required:["table","id"],type:"object"},L=[{annotations:{...le,title:"Find rows related to a row"},description:"Follow the schema's foreign keys out of one row and return the rows it is connected to, each with its hop distance, the edge names walked to reach it, and a depth-decaying score. Use this to answer 'what is connected to this' — a customer's tickets, those tickets' messages — which keyword and semantic search cannot, because the connection lives in a foreign key rather than in the text. Read-only, but it reads through the deployment's ADMIN writer: RLS policies and column masks do not apply to what it returns.",inputSchema:ue,name:"lunora_find_related"}],he=new Set(L.map(e=>e.name)),pe=e=>{const{cursor:t,depth:n,direction:o,edges:i,limit:r}=e;if(t!=null&&typeof t!="string")throw new c("BAD_REQUEST","findRelated: `cursor` must be a string");if(n!==void 0&&typeof n!="number")throw new c("BAD_REQUEST","findRelated: `depth` must be a number");if(o!==void 0&&o!=="both"&&o!=="in"&&o!=="out")throw new c("BAD_REQUEST",'findRelated: `direction` must be one of "in", "out" or "both"');if(r!==void 0&&typeof r!="number")throw new c("BAD_REQUEST","findRelated: `limit` must be a number");if(i!==void 0&&(!Array.isArray(i)||!i.every(s=>typeof s=="string")))throw new c("BAD_REQUEST","findRelated: `edges` must be an array of edge-name strings")},fe=e=>{const{cursor:t,depth:n,direction:o,edges:i,id:r,limit:s,shardKey:a,table:d}=e;if(typeof d!="string"||d.trim()==="")throw new c("BAD_REQUEST","findRelated: `table` is required");if(typeof r!="string"||r.trim()==="")throw new c("BAD_REQUEST","findRelated: `id` is required");if(pe(e),a!==void 0&&(typeof a!="string"||a.trim()===""))throw new c("BAD_REQUEST","findRelated: `shardKey` must be a non-empty string when given");return{args:{id:r,table:d,...typeof t=="string"?{cursor:t}:{},...n===void 0?{}:{depth:n},...o===void 0?{}:{direction:o},...i===void 0?{}:{edges:i},...s===void 0?{}:{limit:s}},shardKey:a}},me=async(e,t,n)=>{if(t!=="lunora_find_related")throw new c("INTERNAL",`unknown row-read tool: ${t}`);const{args:o,shardKey:i}=fe(n),r={__lunoraRef:ee.findRelated};return u(await e.query(r,o,{...i===void 0?{}:{shardKey:i}}))},w=new TextEncoder,ge=Array.from({length:32},(e,t)=>t);new RegExp(`[${ge.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const ye=64,we=new Map,k=async e=>te(we,e,async()=>crypto.subtle.importKey("raw",w.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),ye),_e=async(e,t)=>{const n=await k(e),o=await crypto.subtle.sign("HMAC",n,w.encode(t));return G(new Uint8Array(o))},be=async(e,t,n)=>{const o=await k(e);return crypto.subtle.verify("HMAC",o,n,w.encode(t))},Ee=/["\\\u0000-\u001F\uD800-\uDFFF]/,A=e=>Ee.test(e)?JSON.stringify(e):`"${e}"`,m=e=>{if(e===void 0)return"null";if(typeof e=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof e=="number"){if(Number.isNaN(e))return"nan";if(e===1/0)return"inf";if(e===-1/0)return"-inf";if(Object.is(e,-0))return"-0"}if(typeof e=="string")return A(e);if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e)){let s="[";for(let a=0;a<e.length;a++)a>0&&(s+=","),s+=m(e[a]);return s+"]"}const t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype){const s=e.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${s} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const n=e,o=Object.keys(n).sort();let i="{",r=!0;for(const s of o){const a=n[s];a!==void 0&&(r?r=!1:i+=",",i+=A(s),i+=":",i+=m(a))}return i+"}"},Ae="lunora-mcp-write-confirmation-v1",U=600*1e3,H=".",P=e=>{const t=e.getAuthToken();if(t===null||t==="")throw new c("UNAUTHORIZED","write confirmation needs the deployment's admin token: it is the secret half of the digest key, and without it a digest would be forgeable by anyone.");return`${Ae}\0${e.url}\0${t}`},x=(e,t)=>`${m(e)}\0${String(t)}`,Oe=async(e,t)=>{const n=Date.now()+U,o=await _e(P(e),x(t,n));return{actionDigest:`${String(n)}${H}${o}`,expiresAt:n}},Te=async(e,t,n)=>{const o=n.indexOf(H);if(o<=0)return"mismatch";const i=Number(n.slice(0,o));if(!Number.isSafeInteger(i)||i<=0)return"mismatch";if(Date.now()>=i)return"expired";let r;try{r=V(n.slice(o+1))}catch{return"mismatch"}return await be(P(e),x(t,i),r)?"valid":"mismatch"},Re="Optional caller-chosen token folded into the digest. GUARANTEE: a retry after a client timeout can resubmit the confirmation you already hold, for as long as that digest is inside its window, instead of asking for a second review — and a deliberately-repeated identical write sent under a NEW key gets its own digest, so it cannot ride the first review. NOT GUARANTEED: this does not deduplicate the write. The server keeps no state between requests and never forwards the key to the function, so a resubmitted confirmed call executes again. Make the function itself idempotent if the write must happen at most once.",Se={actionDigest:{description:"The digest returned by the preceding action_required result. Required together with confirmed, and only valid until the expiresAt that result reported — past that, propose again.",type:"string"},confirmed:{description:"Set to true ONLY on the second call, after a human has reviewed the proposed action, and only together with the actionDigest that proposal returned. Omit it on the first call. The server cannot tell whether a human actually reviewed it — that is this client's responsibility, and the operator enabled writes on the understanding that this client asks.",type:"boolean"},idempotencyKey:{description:Re,type:"string"}},Ne=e=>{const t=typeof e.actionDigest=="string"&&e.actionDigest.length>0?e.actionDigest:void 0,n=typeof e.idempotencyKey=="string"&&e.idempotencyKey.length>0?e.idempotencyKey:void 0;return{actionDigest:t,confirmed:e.confirmed===!0,idempotencyKey:n}},ve=(e,t)=>u({actionDigest:t.actionDigest,expiresAt:new Date(t.expiresAt).toISOString(),nextStep:`Show proposedAction to a human. To execute, call ${e.tool} again with the IDENTICAL functionPath, args, shardKey and idempotencyKey, plus confirmed: true and this actionDigest, before expiresAt. Nothing has been written or called yet.`,proposedAction:e,status:"action_required"}),Ie=async(e,t,n)=>{if(!n.confirmed||n.actionDigest===void 0)return ve(t,await Oe(e,t));const o=await Te(e,t,n.actionDigest);if(o!=="valid")return o==="expired"?l(`confirmation rejected: this actionDigest has expired. A confirmation is good for ${String(U/6e4)} minutes from the proposal that issued it, so an approval cannot be replayed in a later session. Nothing was written. Call ${t.tool} again WITHOUT confirmed to get a fresh actionDigest, have it reviewed, then resubmit those same arguments with it.`):l(`confirmation rejected: the actionDigest does not match this call. A digest is bound to the exact tool, function path, arguments, shard key and idempotency key it was issued for, so any edit to the proposal invalidates it — and a digest from another deployment never matches. Nothing was written. Call ${t.tool} again WITHOUT confirmed to get a fresh actionDigest for the current arguments, have it reviewed, then resubmit those same arguments with it.`)},M={properties:{args:{description:"Arguments object passed to the function",type:"object"},functionPath:{description:'Function reference, e.g. "messages:send"',type:"string"},shardKey:{description:"Optional shard key when the function is .shardBy()-partitioned",type:"string"}},required:["functionPath"],type:"object"},O={properties:{},type:"object"},De={properties:{functionPath:{description:'Function reference, e.g. "messages:send"',type:"string"}},required:["functionPath"],type:"object"},h={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},$=[{annotations:{...h,title:"List deployment functions"},description:"List the deployment's public functions (queries, mutations, actions) with their kinds.",inputSchema:O,name:"lunora_list_functions"},{annotations:{...h,title:"List global tables"},description:"List the deployment's .global() tables with their row counts. Names and row counts only — no column shapes.",inputSchema:O,name:"lunora_list_tables"},{annotations:{...h,title:"Describe a function's arguments"},description:"Return a function's argument descriptors (name, validator kind, whether it is optional) and its kind, so a caller can construct a valid arguments object. Call lunora_list_functions first to discover available function paths.",inputSchema:De,name:"lunora_get_function_schema"},{annotations:{...h,title:"Run a query"},description:"Run a query and return its result. Read-only.",inputSchema:M,name:"lunora_run_query"}],Ce=new Set($.map(e=>e.name)),T={properties:{...M.properties,...Se},required:["functionPath"],type:"object"},R='TWO-STEP: the first call does NOT execute. It returns status "action_required" with the proposed action, an actionDigest and the expiresAt it is good until; show that to a human, then call again before expiresAt with the IDENTICAL functionPath/args/shardKey plus confirmed: true and that actionDigest. Any change to the target or the arguments produces a different digest and needs a fresh review, and an expired digest is refused rather than re-proposed.',F=[{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:"Run a mutation (writes data)"},description:`Run a mutation. Writes data. ${R}`,inputSchema:T,name:"lunora_run_mutation"},{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:"Run an action (may call external services)"},description:`Run an action. May call external services — send mail, charge a card, hit a third-party API — so the confirmation is the only thing between a proposal and a real-world side effect. ${R}`,inputSchema:T,name:"lunora_run_action"}],Le=new Set(F.map(e=>e.name)),K=e=>{const{functionPath:t}=e;if(typeof t!="string"||t.length===0)throw new c("BAD_REQUEST",'"functionPath" is required and must be a non-empty string');return t},S=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),N=e=>Array.isArray(e)?"an array":`a ${typeof e}`,ke=e=>{if(e==null)return{};if(typeof e=="string"){let t;try{t=JSON.parse(e)}catch{throw new c("BAD_REQUEST",'"args" must be a JSON object; received a string that is not valid JSON')}if(!S(t))throw new c("BAD_REQUEST",`"args" must be a JSON object; the provided string decoded to ${N(t)}`);return t}if(!S(e))throw new c("BAD_REQUEST",`"args" must be a JSON object, got ${N(e)}`);return e},W=e=>{const t=K(e),n=ke(e.args),o=typeof e.shardKey=="string"&&e.shardKey.length>0?e.shardKey:void 0;return{args:n,functionPath:t,shardKey:o}},g=e=>({__lunoraRef:e}),Ue=3e4,p=new WeakMap,y=e=>{const t=Date.now(),n=p.get(e);if(n!==void 0&&n.expiresAt>t)return n.promise;const o=e.listFunctions().catch(i=>{throw p.get(e)?.promise===o&&p.delete(e),i});return p.set(e,{expiresAt:t+Ue,promise:o}),o},j=async(e,t,n)=>{const i=(await y(e)).find(r=>r.path===t);if(i===void 0)throw new c("NOT_FOUND",`function not found or not public: ${t}`);if(i.kind!==n)throw new c("BAD_REQUEST",`function ${t} is a ${i.kind}, not a ${n}`)},He=async(e,t,n,o,i)=>{const r=Ne(i);return Ie(e,{...o,idempotencyKey:r.idempotencyKey,kind:n,tool:t},r)},Pe=async(e,t,n)=>{switch(t){case"lunora_get_function_schema":{const o=K(n),r=(await y(e)).find(s=>s.path===o);return r===void 0?l(`function not found: ${o}`):u({args:r.args??[],kind:r.kind,path:r.path})}case"lunora_list_functions":return u(await y(e));case"lunora_list_tables":return u(await e.listGlobalTables());case"lunora_run_query":{const{args:o,functionPath:i,shardKey:r}=W(n);return await j(e,i,"query"),u(await e.query(g(i),o,{shardKey:r}))}default:throw new c("INTERNAL",`unknown read-only tool: ${t}`)}},xe=async(e,t,n)=>{if(t!=="lunora_run_action"&&t!=="lunora_run_mutation")throw new c("INTERNAL",`unknown write tool: ${t}`);const o=t==="lunora_run_action"?"action":"mutation",{args:i,functionPath:r,shardKey:s}=W(n);await j(e,r,o);const a=await He(e,t,o,{args:i,functionPath:r,shardKey:s},n);return a!==void 0?a:u(o==="action"?await e.action(g(r),i,{shardKey:s}):await e.mutation(g(r),i,{shardKey:s}))},v="lunora:data-read",I="lunora:observability",Me=e=>e===!0,f=[{call:Pe,definitions:$,names:Ce},{call:(e,t,n)=>de(t,n),definitions:C,names:re},{call:me,definitions:L,gate:{flag:"allowDataReads",refuse:e=>`tool "${e}" is disabled: it returns raw table rows read through the deployment's ADMIN writer, so RLS policies and column masks do not apply. Enable it with the LUNORA_MCP_ALLOW_DATA_READS env var or the allowDataReads option; on the authed path the token also needs the ${v} scope.`,scope:v},names:he},{call:Z,definitions:z,gate:{flag:"allowObservability",refuse:e=>`tool "${e}" is disabled: it reads the deployment's logs, request metadata and grouped errors — user data that would land at the model provider. Enable it with the LUNORA_MCP_ALLOW_OBSERVABILITY env var or the allowObservability option; on the authed path the token also needs the ${I} scope.`,scope:I},names:X},{call:xe,definitions:F,gate:{flag:"allowWrites",refuse:e=>`tool "${e}" is disabled: this MCP server is read-only. Enable writes with the LUNORA_MCP_ALLOW_WRITES env var.`},names:Le}],_=(e,t)=>e.gate!==void 0&&!Me(t[e.gate.flag])?e.gate:void 0,je=(e,t=!1,n=!1)=>{const o={allowDataReads:n,allowObservability:t,allowWrites:e};return f.filter(i=>_(i,o)===void 0).flatMap(i=>i.definitions)},Be=async(e,t,n,o=!1,i=!1,r=!1)=>{const s=f.find(d=>d.names.has(t));if(s===void 0)return l(`unknown tool: ${t}`);const a=_(s,{allowDataReads:r,allowObservability:i,allowWrites:o});if(a!==void 0)return l(a.refuse(t));try{return await s.call(e,t,n)}catch(d){const B=d instanceof Error?d.message:String(d);return l(B)}},qe=(e,t)=>{const n=f.find(o=>o.names.has(e));if(!(n?.gate?.scope===void 0||_(n,t)!==void 0))return n.gate.scope},Qe=f.flatMap(e=>e.gate?.scope===void 0?[]:[{flag:e.gate.flag,scope:e.gate.scope}]);export{v as D,C as E,I as O,$ as R,Qe as S,F as W,Le as a,de as b,Be as c,re as d,L as e,qe as s,je as t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/mcp",
3
- "version": "1.0.0-alpha.229",
3
+ "version": "1.0.0-alpha.230",
4
4
  "description": "Model Context Protocol server exposing a Lunora deployment to AI agents",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -54,9 +54,9 @@
54
54
  },
55
55
  "dependencies": {
56
56
  "@cfworker/json-schema": "^4.1.1",
57
- "@lunora/client": "1.0.0-alpha.196",
57
+ "@lunora/client": "1.0.0-alpha.197",
58
58
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
59
- "@lunora/shard-engine": "1.0.0-alpha.119",
59
+ "@lunora/shard-engine": "1.0.0-alpha.120",
60
60
  "@modelcontextprotocol/sdk": "^1.32.0"
61
61
  },
62
62
  "peerDependencies": {
@@ -1 +0,0 @@
1
- import{R as T,e as _,W as E,a as N,c as a,t as o}from"./tools-CFdbSZHO.mjs";import{O as D}from"./observability-tools-D4Z8dGS-.mjs";export{D as OBSERVABILITY_TOOL_DEFINITIONS,T as READ_ONLY_TOOL_DEFINITIONS,_ as ROW_READ_TOOL_DEFINITIONS,E as WRITE_TOOL_DEFINITIONS,N as WRITE_TOOL_NAMES,a as callTool,o as toolDefinitions};
@@ -1 +0,0 @@
1
- import{LunoraError as l}from"@lunora/errors";import{isAgentToolName as m}from"./AGENT_RUN_INPUT_SCHEMA-hKbpa3Dg.mjs";import{readScreenedBody as h,serveStateless as u}from"./DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{resolveClient as v,createLunoraMcpServer as y}from"./connectStdio-Cpwf1Lbw.mjs";import{c as S}from"./tool-call-Bs-QeKp6.mjs";import{a as g}from"./tools-CFdbSZHO.mjs";const w=e=>typeof e.scope!="string"?new Set:new Set(e.scope.split(" ").filter(s=>s!=="")),B=e=>{const{maxRequestBytes:s,stepUp:r}=e;if(r!==void 0&&(typeof r.scope!="string"||r.scope===""||typeof r.challenge!="function"))throw new l("MCP_STEP_UP_MISCONFIGURED","createAuthedMcpFetchHandler: `stepUp` needs a non-empty `scope` and a `challenge` function.");const i=typeof e.server=="function"?void 0:v(e.server);return e.protect(async(c,a)=>{const p=typeof e.server=="function"?await e.server(a):{...e.server,client:i};let t;if(r!==void 0){const o=await h(c,s);if("response"in o)return o.response;({parsedBody:t}=o);const f=p.agents??[];if((Array.isArray(t)?t:[t]).some(d=>{const n=S(d);return n!==void 0&&(g.has(n)||m(n,f))})&&!w(a).has(r.scope))throw r.challenge([r.scope])}return await u(y(p),c,{maxRequestBytes:s,parsedBody:t})})};export{B as createAuthedMcpFetchHandler,w as mcpTokenScopes};
@@ -1,2 +0,0 @@
1
- import{getCatalogEntry as j,resolveHint as q,findIssueSolution as B,isInternalCode as N,LunoraError as c}from"@lunora/errors";import{e as l,o as Q,a as u,t as Y,f as J,b as G,O as V,c as X}from"./observability-tools-D4Z8dGS-.mjs";import{ADMIN_FUNCTIONS as z}from"@lunora/shard-engine";import{m as Z}from"./promise-memo-OqVPWoUX.mjs";const ee={destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},w="https://lunora.sh/docs/errors",te={properties:{code:{description:'The error code to explain, e.g. "CONFLICT" or "RLS_REQUIRED". Case-sensitive; codes are SCREAMING_SNAKE_CASE.',type:"string"},message:{description:"The raw error message, when there is no code (codegen and Cloudflare platform errors arrive as plain text). Matched against the solution tables.",type:"string"}},type:"object"},ne={properties:{code:{description:"The code that was looked up, when one was given.",type:"string"},docsUrl:{description:"Link to this code's section of the published error reference.",type:"string"},found:{description:"False when neither the code nor the message matched anything — the other fields are then absent.",type:"boolean"},hint:{description:"Actionable Markdown remediation, when the catalog or a message rule has one.",type:"string"},internal:{description:"True when the code is redacted on the wire: its real message is logged server-side and never reaches a client, so it is absent from the published reference.",type:"boolean"},solution:{description:"A message-matched solution: { id, header, body }, from Lunora's rules or the Cloudflare platform table.",type:"object"},status:{description:"HTTP/RPC status this code maps to on the wire.",type:"number"},title:{description:"Short human-readable summary of the code.",type:"string"}},required:["found"],type:"object"},S=[{annotations:{...ee,title:"Explain a Lunora error"},description:"Explain a Lunora error before guessing at a fix: pass its code (CONFLICT, RLS_REQUIRED, …) or the raw error message, and get the catalog's transport status, title and actionable hint, plus any matched codegen/Cloudflare solution and a link to the reference. Static catalog data — no deployment and no credentials needed.",inputSchema:te,name:"lunora_explain_error",outputSchema:ne}],oe=new Set(S.map(e=>e.name)),_=e=>typeof e=="string"&&e.length>0?e:void 0,ie=e=>typeof e=="string"?e:e.join(`
2
- `),re=(e,t)=>t?.docsUrl!==void 0?t.docsUrl:e===void 0||t===void 0||N(e)?w:`${w}#${e.toLowerCase()}`,se=(e,t)=>{const n=e===void 0?void 0:j(e),o=e===void 0?void 0:q({code:e}),i=t===void 0?void 0:B(t),r={docsUrl:re(e,n),found:n!==void 0||i!==void 0};return e!==void 0&&(r.code=e,N(e)&&(r.internal=!0)),n!==void 0&&(r.status=n.status,r.title=n.title),o!==void 0&&(r.hint=ie(o)),i!==void 0&&(r.solution={body:i.body,header:i.header,id:i.id}),r},ae=(e,t)=>{if(e!=="lunora_explain_error")return l(`unknown error tool: ${e}`);const n=_(t.code),o=_(t.message);return n===void 0&&o===void 0?l('lunora_explain_error needs a "code" or a "message" (or both); received neither.'):Q(se(n,o))},ce={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},de={properties:{cursor:{description:"Opaque cursor from a previous call's continueCursor, to fetch the next page.",type:"string"},depth:{description:"How many hops to follow. 1 (default) is the direct neighbourhood; maximum 4.",type:"number"},direction:{description:'Which way to follow foreign keys: "out" follows the ids this row holds (ticket → customer), "in" the rows that point at it (customer → tickets), "both" (default) does both.',type:"string"},edges:{description:'Restrict the walk to these edge names, each "<table>.<column>" (e.g. "tickets.customerId"). Omit to follow every declared foreign key.',items:{type:"string"},type:"array"},id:{description:"Document id of the row to start from.",type:"string"},limit:{description:"Maximum related rows to return (default 50, maximum 200).",type:"number"},shardKey:{description:"Shard to read from on a .shardBy()-partitioned deployment. Omit for the default (unsharded) shard.",type:"string"},table:{description:'Table the start row lives in, e.g. "customers".',type:"string"}},required:["table","id"],type:"object"},v=[{annotations:{...ce,title:"Find rows related to a row"},description:"Follow the schema's foreign keys out of one row and return the rows it is connected to, each with its hop distance, the edge names walked to reach it, and a depth-decaying score. Use this to answer 'what is connected to this' — a customer's tickets, those tickets' messages — which keyword and semantic search cannot, because the connection lives in a foreign key rather than in the text. Read-only, but it reads through the deployment's ADMIN writer: RLS policies and column masks do not apply to what it returns.",inputSchema:de,name:"lunora_find_related"}],le=new Set(v.map(e=>e.name)),ue=e=>{const{cursor:t,depth:n,direction:o,edges:i,limit:r}=e;if(t!=null&&typeof t!="string")throw new c("BAD_REQUEST","findRelated: `cursor` must be a string");if(n!==void 0&&typeof n!="number")throw new c("BAD_REQUEST","findRelated: `depth` must be a number");if(o!==void 0&&o!=="both"&&o!=="in"&&o!=="out")throw new c("BAD_REQUEST",'findRelated: `direction` must be one of "in", "out" or "both"');if(r!==void 0&&typeof r!="number")throw new c("BAD_REQUEST","findRelated: `limit` must be a number");if(i!==void 0&&(!Array.isArray(i)||!i.every(s=>typeof s=="string")))throw new c("BAD_REQUEST","findRelated: `edges` must be an array of edge-name strings")},he=e=>{const{cursor:t,depth:n,direction:o,edges:i,id:r,limit:s,shardKey:a,table:d}=e;if(typeof d!="string"||d.trim()==="")throw new c("BAD_REQUEST","findRelated: `table` is required");if(typeof r!="string"||r.trim()==="")throw new c("BAD_REQUEST","findRelated: `id` is required");if(ue(e),a!==void 0&&(typeof a!="string"||a.trim()===""))throw new c("BAD_REQUEST","findRelated: `shardKey` must be a non-empty string when given");return{args:{id:r,table:d,...typeof t=="string"?{cursor:t}:{},...n===void 0?{}:{depth:n},...o===void 0?{}:{direction:o},...i===void 0?{}:{edges:i},...s===void 0?{}:{limit:s}},shardKey:a}},fe=async(e,t,n)=>{if(t!=="lunora_find_related")throw new c("INTERNAL",`unknown row-read tool: ${t}`);const{args:o,shardKey:i}=he(n),r={__lunoraRef:z.findRelated};return u(await e.query(r,o,{...i===void 0?{}:{shardKey:i}}))},g=new TextEncoder,pe=Array.from({length:32},(e,t)=>t);new RegExp(`[${pe.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const me=64,ye=new Map,I=async e=>Z(ye,e,async()=>crypto.subtle.importKey("raw",g.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),me),ge=async(e,t)=>{const n=await I(e),o=await crypto.subtle.sign("HMAC",n,g.encode(t));return Y(new Uint8Array(o))},we=async(e,t,n)=>{const o=await I(e);return crypto.subtle.verify("HMAC",o,n,g.encode(t))},_e=/["\\\u0000-\u001F\uD800-\uDFFF]/,b=e=>_e.test(e)?JSON.stringify(e):`"${e}"`,p=e=>{if(e===void 0)return"null";if(typeof e=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof e=="number"){if(Number.isNaN(e))return"nan";if(e===1/0)return"inf";if(e===-1/0)return"-inf";if(Object.is(e,-0))return"-0"}if(typeof e=="string")return b(e);if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e)){let s="[";for(let a=0;a<e.length;a++)a>0&&(s+=","),s+=p(e[a]);return s+"]"}const t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype){const s=e.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${s} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const n=e,o=Object.keys(n).sort();let i="{",r=!0;for(const s of o){const a=n[s];a!==void 0&&(r?r=!1:i+=",",i+=b(s),i+=":",i+=p(a))}return i+"}"},be="lunora-mcp-write-confirmation-v1",D=600*1e3,C=".",L=e=>{const t=e.getAuthToken();if(t===null||t==="")throw new c("UNAUTHORIZED","write confirmation needs the deployment's admin token: it is the secret half of the digest key, and without it a digest would be forgeable by anyone.");return`${be}\0${e.url}\0${t}`},k=(e,t)=>`${p(e)}\0${String(t)}`,Ee=async(e,t)=>{const n=Date.now()+D,o=await ge(L(e),k(t,n));return{actionDigest:`${String(n)}${C}${o}`,expiresAt:n}},Ae=async(e,t,n)=>{const o=n.indexOf(C);if(o<=0)return"mismatch";const i=Number(n.slice(0,o));if(!Number.isSafeInteger(i)||i<=0)return"mismatch";if(Date.now()>=i)return"expired";let r;try{r=J(n.slice(o+1))}catch{return"mismatch"}return await we(L(e),k(t,i),r)?"valid":"mismatch"},Oe="Optional caller-chosen token folded into the digest. GUARANTEE: a retry after a client timeout can resubmit the confirmation you already hold, for as long as that digest is inside its window, instead of asking for a second review — and a deliberately-repeated identical write sent under a NEW key gets its own digest, so it cannot ride the first review. NOT GUARANTEED: this does not deduplicate the write. The server keeps no state between requests and never forwards the key to the function, so a resubmitted confirmed call executes again. Make the function itself idempotent if the write must happen at most once.",Te={actionDigest:{description:"The digest returned by the preceding action_required result. Required together with confirmed, and only valid until the expiresAt that result reported — past that, propose again.",type:"string"},confirmed:{description:"Set to true ONLY on the second call, after a human has reviewed the proposed action, and only together with the actionDigest that proposal returned. Omit it on the first call. The server cannot tell whether a human actually reviewed it — that is this client's responsibility, and the operator enabled writes on the understanding that this client asks.",type:"boolean"},idempotencyKey:{description:Oe,type:"string"}},Re=e=>{const t=typeof e.actionDigest=="string"&&e.actionDigest.length>0?e.actionDigest:void 0,n=typeof e.idempotencyKey=="string"&&e.idempotencyKey.length>0?e.idempotencyKey:void 0;return{actionDigest:t,confirmed:e.confirmed===!0,idempotencyKey:n}},Ne=(e,t)=>u({actionDigest:t.actionDigest,expiresAt:new Date(t.expiresAt).toISOString(),nextStep:`Show proposedAction to a human. To execute, call ${e.tool} again with the IDENTICAL functionPath, args, shardKey and idempotencyKey, plus confirmed: true and this actionDigest, before expiresAt. Nothing has been written or called yet.`,proposedAction:e,status:"action_required"}),Se=async(e,t,n)=>{if(!n.confirmed||n.actionDigest===void 0)return Ne(t,await Ee(e,t));const o=await Ae(e,t,n.actionDigest);if(o!=="valid")return o==="expired"?l(`confirmation rejected: this actionDigest has expired. A confirmation is good for ${String(D/6e4)} minutes from the proposal that issued it, so an approval cannot be replayed in a later session. Nothing was written. Call ${t.tool} again WITHOUT confirmed to get a fresh actionDigest, have it reviewed, then resubmit those same arguments with it.`):l(`confirmation rejected: the actionDigest does not match this call. A digest is bound to the exact tool, function path, arguments, shard key and idempotency key it was issued for, so any edit to the proposal invalidates it — and a digest from another deployment never matches. Nothing was written. Call ${t.tool} again WITHOUT confirmed to get a fresh actionDigest for the current arguments, have it reviewed, then resubmit those same arguments with it.`)},U={properties:{args:{description:"Arguments object passed to the function",type:"object"},functionPath:{description:'Function reference, e.g. "messages:send"',type:"string"},shardKey:{description:"Optional shard key when the function is .shardBy()-partitioned",type:"string"}},required:["functionPath"],type:"object"},E={properties:{},type:"object"},ve={properties:{functionPath:{description:'Function reference, e.g. "messages:send"',type:"string"}},required:["functionPath"],type:"object"},h={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},H=[{annotations:{...h,title:"List deployment functions"},description:"List the deployment's public functions (queries, mutations, actions) with their kinds.",inputSchema:E,name:"lunora_list_functions"},{annotations:{...h,title:"List global tables"},description:"List the deployment's .global() tables with their row counts. Names and row counts only — no column shapes.",inputSchema:E,name:"lunora_list_tables"},{annotations:{...h,title:"Describe a function's arguments"},description:"Return a function's argument descriptors (name, validator kind, whether it is optional) and its kind, so a caller can construct a valid arguments object. Call lunora_list_functions first to discover available function paths.",inputSchema:ve,name:"lunora_get_function_schema"},{annotations:{...h,title:"Run a query"},description:"Run a query and return its result. Read-only.",inputSchema:U,name:"lunora_run_query"}],Ie=new Set(H.map(e=>e.name)),A={properties:{...U.properties,...Te},required:["functionPath"],type:"object"},O='TWO-STEP: the first call does NOT execute. It returns status "action_required" with the proposed action, an actionDigest and the expiresAt it is good until; show that to a human, then call again before expiresAt with the IDENTICAL functionPath/args/shardKey plus confirmed: true and that actionDigest. Any change to the target or the arguments produces a different digest and needs a fresh review, and an expired digest is refused rather than re-proposed.',P=[{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:"Run a mutation (writes data)"},description:`Run a mutation. Writes data. ${O}`,inputSchema:A,name:"lunora_run_mutation"},{annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:"Run an action (may call external services)"},description:`Run an action. May call external services — send mail, charge a card, hit a third-party API — so the confirmation is the only thing between a proposal and a real-world side effect. ${O}`,inputSchema:A,name:"lunora_run_action"}],De=new Set(P.map(e=>e.name)),x=e=>{const{functionPath:t}=e;if(typeof t!="string"||t.length===0)throw new c("BAD_REQUEST",'"functionPath" is required and must be a non-empty string');return t},T=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),R=e=>Array.isArray(e)?"an array":`a ${typeof e}`,Ce=e=>{if(e==null)return{};if(typeof e=="string"){let t;try{t=JSON.parse(e)}catch{throw new c("BAD_REQUEST",'"args" must be a JSON object; received a string that is not valid JSON')}if(!T(t))throw new c("BAD_REQUEST",`"args" must be a JSON object; the provided string decoded to ${R(t)}`);return t}if(!T(e))throw new c("BAD_REQUEST",`"args" must be a JSON object, got ${R(e)}`);return e},M=e=>{const t=x(e),n=Ce(e.args),o=typeof e.shardKey=="string"&&e.shardKey.length>0?e.shardKey:void 0;return{args:n,functionPath:t,shardKey:o}},m=e=>({__lunoraRef:e}),Le=3e4,f=new WeakMap,y=e=>{const t=Date.now(),n=f.get(e);if(n!==void 0&&n.expiresAt>t)return n.promise;const o=e.listFunctions().catch(i=>{throw f.get(e)?.promise===o&&f.delete(e),i});return f.set(e,{expiresAt:t+Le,promise:o}),o},$=async(e,t,n)=>{const i=(await y(e)).find(r=>r.path===t);if(i===void 0)throw new c("NOT_FOUND",`function not found or not public: ${t}`);if(i.kind!==n)throw new c("BAD_REQUEST",`function ${t} is a ${i.kind}, not a ${n}`)},ke=async(e,t,n,o,i)=>{const r=Re(i);return Se(e,{...o,idempotencyKey:r.idempotencyKey,kind:n,tool:t},r)},Ue=async(e,t,n)=>{switch(t){case"lunora_get_function_schema":{const o=x(n),r=(await y(e)).find(s=>s.path===o);return r===void 0?l(`function not found: ${o}`):u({args:r.args??[],kind:r.kind,path:r.path})}case"lunora_list_functions":return u(await y(e));case"lunora_list_tables":return u(await e.listGlobalTables());case"lunora_run_query":{const{args:o,functionPath:i,shardKey:r}=M(n);return await $(e,i,"query"),u(await e.query(m(i),o,{shardKey:r}))}default:throw new c("INTERNAL",`unknown read-only tool: ${t}`)}},He=async(e,t,n)=>{if(t!=="lunora_run_action"&&t!=="lunora_run_mutation")throw new c("INTERNAL",`unknown write tool: ${t}`);const o=t==="lunora_run_action"?"action":"mutation",{args:i,functionPath:r,shardKey:s}=M(n);await $(e,r,o);const a=await ke(e,t,o,{args:i,functionPath:r,shardKey:s},n);return a!==void 0?a:u(o==="action"?await e.action(m(r),i,{shardKey:s}):await e.mutation(m(r),i,{shardKey:s}))},Pe=e=>e===!0,K=[{call:Ue,definitions:H,names:Ie},{call:(e,t,n)=>ae(t,n),definitions:S,names:oe},{call:fe,definitions:v,gate:{flag:"allowDataReads",refuse:e=>`tool "${e}" is disabled: it returns raw table rows read through the deployment's ADMIN writer, so RLS policies and column masks do not apply. Enable it with the LUNORA_MCP_ALLOW_DATA_READS env var.`},names:le},{call:X,definitions:V,gate:{flag:"allowObservability",refuse:e=>`tool "${e}" is disabled: it reads the deployment's logs, request metadata and grouped errors — user data that would land at the model provider. Enable it with the LUNORA_MCP_ALLOW_OBSERVABILITY env var.`},names:G},{call:He,definitions:P,gate:{flag:"allowWrites",refuse:e=>`tool "${e}" is disabled: this MCP server is read-only. Enable writes with the LUNORA_MCP_ALLOW_WRITES env var.`},names:De}],F=(e,t)=>e.gate!==void 0&&!Pe(t[e.gate.flag])?e.gate:void 0,Fe=(e,t=!1,n=!1)=>{const o={allowDataReads:n,allowObservability:t,allowWrites:e};return K.filter(i=>F(i,o)===void 0).flatMap(i=>i.definitions)},We=async(e,t,n,o=!1,i=!1,r=!1)=>{const s=K.find(d=>d.names.has(t));if(s===void 0)return l(`unknown tool: ${t}`);const a=F(s,{allowDataReads:r,allowObservability:i,allowWrites:o});if(a!==void 0)return l(a.refuse(t));try{return await s.call(e,t,n)}catch(d){const W=d instanceof Error?d.message:String(d);return l(W)}};export{S as E,H as R,P as W,De as a,ae as b,We as c,oe as d,v as e,Fe as t};