@lunora/mcp 1.0.0-alpha.240 → 1.0.0-alpha.241

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 (32) hide show
  1. package/dist/bin.mjs +1 -1
  2. package/dist/docs/index.d.mts +4 -3
  3. package/dist/docs/index.d.ts +4 -3
  4. package/dist/index.d.mts +11 -473
  5. package/dist/index.d.ts +11 -473
  6. package/dist/index.mjs +1 -1
  7. package/dist/node/index.d.mts +90 -0
  8. package/dist/node/index.d.ts +90 -0
  9. package/dist/node/index.mjs +1 -0
  10. package/dist/packem_shared/{LOCAL_SERVER_NAME-DM_NJ-eY.mjs → LOCAL_SERVER_NAME-Bj3l_7WG.mjs} +1 -1
  11. package/dist/packem_shared/READ_ONLY_TOOL_DEFINITIONS-CihHZdB6.mjs +1 -0
  12. package/dist/packem_shared/{serve-stateless.d-CKsbI0fP.d.mts → compose.d-BVnP3uAy.d.mts} +1 -44
  13. package/dist/packem_shared/{serve-stateless.d-CKsbI0fP.d.ts → compose.d-BVnP3uAy.d.ts} +1 -44
  14. package/dist/packem_shared/connectStdio-DYI-3vnF.mjs +1 -0
  15. package/dist/packem_shared/createAuthedMcpFetchHandler-D_SQpDhH.mjs +1 -0
  16. package/dist/packem_shared/createLunoraMcpServer-CQJIwdik.mjs +1 -0
  17. package/dist/packem_shared/createMcpFetchHandler-TkLzJUNn.mjs +1 -0
  18. package/dist/packem_shared/createPaidMcpServer-BH_mly77.mjs +1 -0
  19. package/dist/packem_shared/serve-stateless.d-DD5arqFx.d.mts +45 -0
  20. package/dist/packem_shared/serve-stateless.d-DD5arqFx.d.ts +45 -0
  21. package/dist/packem_shared/server.d-D3rejkVc.d.mts +152 -0
  22. package/dist/packem_shared/server.d-DQgZyRkG.d.ts +152 -0
  23. package/dist/packem_shared/{tools-Dmnb3M2T.mjs → tools-BOfWz78m.mjs} +1 -1
  24. package/dist/worker/index.d.mts +258 -0
  25. package/dist/worker/index.d.ts +258 -0
  26. package/dist/worker/index.mjs +1 -0
  27. package/package.json +9 -1
  28. package/dist/packem_shared/READ_ONLY_TOOL_DEFINITIONS-DA4wD25I.mjs +0 -1
  29. package/dist/packem_shared/connectStdio-n-RHjcwN.mjs +0 -1
  30. package/dist/packem_shared/createAuthedMcpFetchHandler-DSTZ2ftz.mjs +0 -1
  31. package/dist/packem_shared/createMcpFetchHandler-CNEfLA-N.mjs +0 -1
  32. package/dist/packem_shared/createPaidMcpServer-C_V1beyQ.mjs +0 -1
@@ -0,0 +1,152 @@
1
+ import { LunoraClient } from '@lunora/client';
2
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
+ import { b as ToolInputSchema, T as ToolDefinition, c as ToolResult } from "./compose.d-BVnP3uAy.js";
4
+ /**
5
+ * Agent exposure for the MCP server: a durable `@lunora/agent` run fronted as an
6
+ * MCP tool an external agent can call. The capability boundary is the MCP-server
7
+ * process + its token, so WHICH agents are exposed is config on the server (like
8
+ * `allowWrites`), not on `defineAgent` — keeping `@lunora/agent` codegen
9
+ * byte-identical.
10
+ */
11
+ interface McpAgentExposure {
12
+ /** What the agent does — shown to the calling model, which decides from it. */
13
+ description: string;
14
+ /** The agent's export name (its `ctx.agents.<name>` / `AGENT_<NAME>` binding). */
15
+ name: string;
16
+ /** Override the model-facing tool name (default `agent_<name>`). */
17
+ toolName?: string;
18
+ }
19
+ /** The generic status/poll tool advertised alongside the per-agent tools. */
20
+ declare const AGENT_STATUS_TOOL_NAME = "lunora_agent_status";
21
+ /**
22
+ * The uniform input schema every agent tool advertises. Agents share ONE run
23
+ * input (`@lunora/agent` has no per-agent validator), so there is nothing to
24
+ * derive per agent — a single static schema is reused for every agent tool.
25
+ */
26
+ declare const AGENT_RUN_INPUT_SCHEMA: ToolInputSchema;
27
+ /**
28
+ * Parse `LUNORA_MCP_AGENTS` — a `;`-separated list of `name:description` pairs,
29
+ * e.g. `"support:Handles support questions;billing:Billing help"`. The
30
+ * description may itself contain colons (only the FIRST colon splits). Blank
31
+ * entries and entries with an empty name/description are skipped.
32
+ */
33
+ declare const parseAgentsEnv: (raw: string | undefined) => McpAgentExposure[];
34
+ /**
35
+ * The tools this module advertises. Fail-closed: only the boolean `true` opts
36
+ * in (an env-plumbed caller could pass a truthy string), and the tools appear
37
+ * ONLY when at least one agent is exposed — so an agent-free or non-opted-in
38
+ * server never lists them.
39
+ */
40
+ declare const agentToolDefinitions: (exposures: ReadonlyArray<McpAgentExposure>, allowAgents: boolean) => ReadonlyArray<ToolDefinition>;
41
+ /** Options threaded into a single agent tool dispatch. */
42
+ interface CallAgentToolOptions {
43
+ /** Opt-in gate — must be exactly `true` or the call is refused fail-closed. */
44
+ allowAgents: boolean;
45
+ /** The exposures advertised by this server. */
46
+ exposures: ReadonlyArray<McpAgentExposure>;
47
+ /** Wall-clock budget a single call awaits before returning a pending result. */
48
+ maxWaitMs?: number;
49
+ /** Delay between thread-status polls. */
50
+ pollIntervalMs?: number;
51
+ /** Test seam replacing the between-poll wait; production uses a real timer. */
52
+ wait?: (ms: number) => Promise<void>;
53
+ }
54
+ /**
55
+ * Dispatch an agent tool call: start a durable run via `agents:agentRun`, then
56
+ * await-with-timeout — poll `agents:agentThread` until terminal (returning the
57
+ * final answer from `agents:agentMessages`) or, on budget exhaustion, return a
58
+ * NON-error pending payload the caller resumes with `lunora_agent_status`.
59
+ *
60
+ * Fail-closed: refused at dispatch unless `allowAgents === true`, mirroring the
61
+ * `allowWrites` guard — starting a run is a side effect and must not ride the
62
+ * read-only default.
63
+ */
64
+ declare const callAgentTool: (client: LunoraClient, name: string, input: Record<string, unknown>, options: CallAgentToolOptions) => Promise<ToolResult>;
65
+ interface LunoraMcpServerOptions {
66
+ /** Wall-clock budget a single agent tool call awaits before returning a pending result. */
67
+ agentMaxWaitMs?: number;
68
+ /** Delay between agent thread-status polls. */
69
+ agentPollIntervalMs?: number;
70
+ /** The agents this server fronts as MCP tools (see `allowAgents`). */
71
+ agents?: ReadonlyArray<McpAgentExposure>;
72
+ /**
73
+ * Expose the per-agent tools (`agent_<name>` + the generic
74
+ * `lunora_agent_status`). Defaults to `false`, mirroring `allowWrites`:
75
+ * starting a durable agent run is a side effect, so the agent tools are
76
+ * omitted from the advertised list AND refused at dispatch unless explicitly
77
+ * opted in. Only takes effect together with a non-empty `agents` list.
78
+ */
79
+ allowAgents?: boolean;
80
+ /**
81
+ * Expose `lunora_find_related`, which returns raw table rows read through the
82
+ * admin writer, so RLS policies and column masks do not apply. Defaults to
83
+ * `false`, for the same reason as `allowObservability`. Only takes effect
84
+ * when a `token` resolved. On the OAuth-protected path the verified token must
85
+ * also carry the data-read scope (see `DATA_READ_SCOPE` in `./tools`).
86
+ */
87
+ allowDataReads?: boolean;
88
+ /**
89
+ * Expose the observability tools (`lunora_get_logs`, `lunora_get_issues`,
90
+ * `lunora_get_advisories`, `lunora_get_query_insights`,
91
+ * `lunora_get_migration_status`). Defaults to `false`, mirroring
92
+ * `allowWrites`: they are read-only, but every row they return — log lines,
93
+ * request metadata, grouped error messages — is production user data that
94
+ * lands in the model's context and therefore at its provider. Holding the
95
+ * admin bearer is not consent to ship that, so it is a separate opt-in;
96
+ * without it the tools are omitted from the advertised list AND refused at
97
+ * dispatch. Only takes effect when a `token` resolved. On the OAuth-protected
98
+ * path the verified token must also carry the observability scope (see
99
+ * `OBSERVABILITY_SCOPE` in `./tools`); this option stays the outer gate.
100
+ */
101
+ allowObservability?: boolean;
102
+ /**
103
+ * Expose the write tools (`lunora_run_mutation` / `lunora_run_action`).
104
+ * Defaults to `false`: the server is READ-ONLY unless explicitly opted in,
105
+ * so a prompt-injected or misaligned agent can't mutate the deployment with
106
+ * the configured token. When false the write tools are omitted from the
107
+ * advertised tool list AND refused at dispatch.
108
+ */
109
+ allowWrites?: boolean;
110
+ /**
111
+ * Pre-built client (test injection). When omitted a `LunoraClient` is
112
+ * created from `url`/`token`/`fetch`.
113
+ */
114
+ client?: LunoraClient;
115
+ /** `fetch` implementation; defaults to the ambient global. */
116
+ fetch?: typeof fetch;
117
+ /**
118
+ * Bearer token sent on every RPC. **Required** alongside `url`, and it must
119
+ * be the deployment's **admin bearer**: the introspection/allowlist path
120
+ * every tool depends on (`lunora_list_functions`, `lunora_list_tables`, and
121
+ * the `assertRunnable` precheck that runs before every `run` tool) hits
122
+ * admin-gated `/_lunora/admin/*` routes, so no scoped/app token works
123
+ * today — it would 403 (`ADMIN_FORBIDDEN`) on the first tool call. The
124
+ * read-only guarantee is therefore NOT enforced by the token's scope; it is
125
+ * enforced in-process via `allowWrites: false` (the default), which omits
126
+ * the write tools from the advertised list and refuses them at dispatch.
127
+ *
128
+ * Because EVERY tool needs it, omitting it is a misconfiguration rather than
129
+ * a reduced-capability mode, and `createLunoraMcpServer` says so at
130
+ * construction instead of advertising a surface that 403s on first use. The
131
+ * one exception is the `client` injection seam (tests / a pre-authenticated
132
+ * client), where this server cannot know what the client can reach and so
133
+ * reads "unknown" fail-closed: the privileged observability tools stay
134
+ * unadvertised and are refused at dispatch.
135
+ */
136
+ token?: string;
137
+ /** Base URL of the deployed Lunora Worker. Required unless `client` is given. */
138
+ url?: string;
139
+ /** Version reported in the `initialize` handshake. Defaults to the version bundled at build time. */
140
+ version?: string;
141
+ }
142
+ /**
143
+ * Build an MCP `Server` whose tools talk to a Lunora deployment. The server is
144
+ * transport-agnostic — call `.connect(transport)` yourself, or use
145
+ * `connectStdio` for the common stdio case.
146
+ *
147
+ * Tool calls are dispatched through `callTool`, which the deployment reaches
148
+ * over HTTP RPC. No WebSocket is opened (the tools never subscribe), so this is
149
+ * safe to run as a short-lived stdio process.
150
+ */
151
+ declare const createLunoraMcpServer: (options: LunoraMcpServerOptions) => Server;
152
+ export { AGENT_RUN_INPUT_SCHEMA as A, CallAgentToolOptions as C, LunoraMcpServerOptions as L, McpAgentExposure as M, AGENT_STATUS_TOOL_NAME as a, agentToolDefinitions as b, callAgentTool as c, createLunoraMcpServer as d, parseAgentsEnv as p };
@@ -1,2 +1,2 @@
1
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};
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,de as a,re as b,Be as c,Le as d,L as e,qe as s,je as t};
@@ -0,0 +1,258 @@
1
+ import { L as LunoraMcpServerOptions } from "../packem_shared/server.d-D3rejkVc.mjs";
2
+ export { A as AGENT_RUN_INPUT_SCHEMA, a as AGENT_STATUS_TOOL_NAME,
3
+ /** Worker-safe entry: fetch handlers and tool composition, with no stdio transport or `node:*` imports. */
4
+ type C as CallAgentToolOptions,
5
+ /** Worker-safe entry: fetch handlers and tool composition, with no stdio transport or `node:*` imports. */
6
+ type M as McpAgentExposure, b as agentToolDefinitions, c as callAgentTool, p as parseAgentsEnv } from "../packem_shared/server.d-D3rejkVc.mjs";
7
+ import { M as McpFetchHandler } from "../packem_shared/serve-stateless.d-DD5arqFx.mjs";
8
+ export { D as DEFAULT_MAX_REQUEST_BYTES, type S as ServeStatelessOptions, s as serveStateless } from "../packem_shared/serve-stateless.d-DD5arqFx.mjs";
9
+ import { T as ToolDefinition, c as ToolResult, b as ToolInputSchema } from "../packem_shared/compose.d-BVnP3uAy.mjs";
10
+ export { type M as McpServerInfo, type a as McpTool, d as createToolServer } from "../packem_shared/compose.d-BVnP3uAy.mjs";
11
+ import { Tool } from '@modelcontextprotocol/sdk/types.js';
12
+ import { LunoraClient } from '@lunora/client';
13
+ import '@modelcontextprotocol/sdk/server/index.js';
14
+ import '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
15
+ /**
16
+ * The observability tools. Descriptions say WHEN to call the tool, not just
17
+ * what it returns — an agent picking between five similar reads needs the
18
+ * trigger, and it pays for these strings on every turn.
19
+ */
20
+ declare const OBSERVABILITY_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
21
+ /** The read-only tool surface: introspection + query. Always exposed. */
22
+ declare const READ_ONLY_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
23
+ /** The write tool surface (mutations + actions). Exposed ONLY when writes are enabled. */
24
+ declare const WRITE_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
25
+ /**
26
+ * The tools this server advertises: every family whose gate is open, in table
27
+ * order. A gated family is OMITTED rather than refused — an AI agent can't
28
+ * invoke what it can't see — and {@link callTool} re-checks the same gate at
29
+ * dispatch, so the guarantee does not depend on a client honouring this list.
30
+ */
31
+ declare const toolDefinitions: (allowWrites: boolean, allowObservability?: boolean, allowDataReads?: boolean) => ReadonlyArray<ToolDefinition>;
32
+ /**
33
+ * Dispatch a tool call against `client`: find the family that owns `name`, check
34
+ * its gate, hand off. Unknown tools and thrown errors are returned as `isError`
35
+ * results (rather than rejections) so the calling model sees the failure as tool
36
+ * output, per the MCP convention.
37
+ *
38
+ * Each gate is enforced HERE as well as in {@link toolDefinitions}, so a call to
39
+ * a gated tool is refused even if the client somehow names one it was never
40
+ * shown.
41
+ */
42
+ declare const callTool: (client: LunoraClient, name: string, input: Record<string, unknown>, allowWrites?: boolean, allowObservability?: boolean, allowDataReads?: boolean) => Promise<ToolResult>;
43
+ /**
44
+ * The verified access-token payload better-auth hands a protected handler.
45
+ *
46
+ * A JWT payload is an open bag of claims, so this is deliberately an index
47
+ * signature with the two entries this module reads named. It is structurally
48
+ * satisfied by `jose`'s `JWTPayload`, which is what better-auth passes.
49
+ */
50
+ interface McpAccessTokenClaims {
51
+ readonly [claim: string]: unknown;
52
+ /** Space-delimited granted scopes (RFC 6749 §3.3). */
53
+ readonly scope?: unknown;
54
+ /** Subject — the user the token was issued for. */
55
+ readonly sub?: string;
56
+ }
57
+ /**
58
+ * The MCP auth gate: wraps a claims-aware handler into a plain fetch handler.
59
+ *
60
+ * Declared structurally here rather than imported from `@better-auth/mcp`,
61
+ * following the same rule `./paid` follows for `@lunora/x402`: a type import
62
+ * from a package this one does not depend on puts that package's `.d.ts` into
63
+ * the build graph, and a consumer that never installs it never builds it
64
+ * either — so the dts bundler looks for a `dist/` that does not exist and fails
65
+ * the build. Structural typing costs nothing here because this module never
66
+ * inspects the gate; it only applies it.
67
+ *
68
+ * Both better-auth entry points partially apply to this shape:
69
+ * `(handler) => requireMcpAuth(auth, handler, opts)` and
70
+ * `(handler) => createMcpProtectedRequestHandler(options, handler)`.
71
+ */
72
+ type McpAuthProtect = (handler: (request: Request, claims: McpAccessTokenClaims) => Promise<Response>) => McpFetchHandler;
73
+ /** Server options, or a function deriving them from the request's verified claims. */
74
+ type AuthedMcpServerOptions = ((claims: McpAccessTokenClaims) => LunoraMcpServerOptions | Promise<LunoraMcpServerOptions>) | LunoraMcpServerOptions;
75
+ interface AuthedMcpFetchHandlerOptions {
76
+ /**
77
+ * Largest accepted request body, in bytes — enforced while the body streams
78
+ * in, not after it is buffered. Defaults to `DEFAULT_MAX_REQUEST_BYTES`
79
+ * (128 KiB), which a value that is not a non-negative safe integer also
80
+ * falls back to.
81
+ */
82
+ maxRequestBytes?: number;
83
+ /**
84
+ * The OAuth gate to mount the MCP server behind. Pass
85
+ * `(handler) => requireMcpAuth(auth, handler, opts)` from
86
+ * `@lunora/auth/plugins`.
87
+ */
88
+ protect: McpAuthProtect;
89
+ /**
90
+ * The Lunora MCP server to serve once a request is authorized — either a
91
+ * fixed options object, or a function of the verified token claims so tool
92
+ * exposure can follow the scopes the token actually carries.
93
+ */
94
+ server: AuthedMcpServerOptions;
95
+ /**
96
+ * Step-up for the side-effecting tools: the write tools
97
+ * (`lunora_run_mutation` / `lunora_run_action`) and the agent tools (each
98
+ * `agent_<name>` and `lunora_agent_status`, since starting a durable run is a
99
+ * side effect). A token without `scope` still sees them in `tools/list`, and
100
+ * a `tools/call` to one throws `challenge([scope])` instead of running, so the
101
+ * client can re-authorize for the scope and retry. Unset, tools follow
102
+ * `allowWrites` / `allowAgents` alone. The raw-row and observability families
103
+ * need their own token scopes with or without `stepUp`; without it a call
104
+ * without the scope is refused as a tool error, not challenged.
105
+ */
106
+ stepUp?: {
107
+ /**
108
+ * Build the error that makes the gate answer 403 `insufficient_scope`
109
+ * naming `scopes`. Pass `createInsufficientScopeError` from
110
+ * `@lunora/auth/plugins`: better-auth only turns an error that factory
111
+ * created into the challenge.
112
+ */
113
+ challenge: (scopes: string[]) => unknown;
114
+ /** The scope a call to a side-effecting tool needs, e.g. `"lunora:write"`. */
115
+ scope: string;
116
+ };
117
+ }
118
+ /**
119
+ * Parse an access token's `scope` claim into a set.
120
+ *
121
+ * RFC 6749 §3.3 makes `scope` a space-delimited string, and better-auth issues
122
+ * it that way; anything else (absent, or a non-string an extension wrote)
123
+ * yields an empty set rather than throwing, so a scope check on a malformed
124
+ * token denies instead of crashing the tool call.
125
+ */
126
+ declare const mcpTokenScopes: (claims: McpAccessTokenClaims) => ReadonlySet<string>;
127
+ declare const createAuthedMcpFetchHandler: (options: AuthedMcpFetchHandlerOptions) => McpFetchHandler;
128
+ /** {@link createMcpFetchHandler} options: the server's, plus this transport's body limit. */
129
+ interface McpFetchHandlerOptions extends LunoraMcpServerOptions {
130
+ /**
131
+ * Largest accepted request body, in bytes — enforced while the body streams
132
+ * in, not after it is buffered. Defaults to `DEFAULT_MAX_REQUEST_BYTES`
133
+ * (128 KiB), which a value that is not a non-negative safe integer also
134
+ * falls back to.
135
+ */
136
+ maxRequestBytes?: number;
137
+ }
138
+ /**
139
+ * Build a stateless Streamable-HTTP fetch handler for a Lunora MCP server. Each
140
+ * invocation constructs a fresh proxy server and serves the request through
141
+ * {@link serveStateless}.
142
+ *
143
+ * The `LunoraClient` is resolved ONCE, here, and shared by every request: it is
144
+ * the same deployment on each one, and the public-function registry memo in
145
+ * `./tools` is keyed by client identity, so a per-request client would re-fetch
146
+ * that registry on every tool call. A misconfiguration (`url` without `token`)
147
+ * therefore throws when the handler is built rather than on first request,
148
+ * which is where `createLunoraMcpServer` already documents reporting it.
149
+ */
150
+ declare const createMcpFetchHandler: (options: McpFetchHandlerOptions) => McpFetchHandler;
151
+ /** A tool handler: receives the call's `arguments` bag, returns an MCP tool result. */
152
+ /**
153
+ * The x402 vocabulary this module needs, declared here rather than imported.
154
+ *
155
+ * The x402 package is an optional peer, and a type import from its `charge`
156
+ * entry puts its `.d.ts` back into this package's build graph:
157
+ * a consumer that never installs x402 never builds it either, so the dts bundler
158
+ * looks for a `dist/` that does not exist and fails. That is not hypothetical —
159
+ * it broke the docs site build, which runs a filtered build over the docs app and its dependency closure
160
+ * and therefore never builds x402.
161
+ *
162
+ * Declaring them locally is safe because this module never *inspects* a charge
163
+ * config; it forwards it whole to `createChargeMiddleware`. The index signature
164
+ * keeps a real charge config assignable as x402 grows fields.
165
+ */
166
+ /** Mirrors x402's `X402Price` — a decimal string like `"$0.05"`, or a number. */
167
+ type X402Price = number | string;
168
+ /** Mirrors x402's charge config with the per-tool price omitted. */
169
+ interface X402ChargeSettings {
170
+ /** Network this resource settles on. */
171
+ readonly network: string;
172
+ /** Everything else x402 accepts, forwarded untouched. */
173
+ readonly [key: string]: unknown;
174
+ /** Payout wallet(s), per network family. */
175
+ readonly recipient: {
176
+ readonly evm?: string;
177
+ readonly svm?: string;
178
+ };
179
+ }
180
+ type ToolHandler = (arguments_: Record<string, unknown>) => Promise<ToolResult> | ToolResult;
181
+ /** Registration shape for a free tool. */
182
+ interface RegisterToolOptions {
183
+ /** Optional MCP tool annotations (`readOnlyHint`, `title`, …). */
184
+ annotations?: Tool["annotations"];
185
+ /** Human/model-facing description of what the tool does. */
186
+ description: string;
187
+ /** JSON-Schema object describing the tool's arguments. */
188
+ inputSchema: ToolInputSchema;
189
+ /** Unique tool name (the MCP `tools/call` `name`). */
190
+ name: string;
191
+ }
192
+ /** Registration shape for a paid tool: a {@link RegisterToolOptions} plus its USD price. */
193
+ interface RegisterPaidToolOptions extends RegisterToolOptions {
194
+ /** USD price per call (e.g. `"$0.05"`), charged via x402 before dispatch. */
195
+ price: X402Price;
196
+ }
197
+ /** x402 settlement vocabulary shared by every paid tool (network, recipient, facilitator); price is per-tool. */
198
+ type PaidMcpChargeConfig = X402ChargeSettings;
199
+ /** Config for `createPaidMcpServer`. */
200
+ interface PaidMcpServerConfig {
201
+ /** The worker-level x402 charge config; each paid tool supplies only its own `price`. */
202
+ charge: PaidMcpChargeConfig;
203
+ /**
204
+ * Largest accepted request body, in bytes — enforced while the body streams
205
+ * in, not after it is buffered. Defaults to `DEFAULT_MAX_REQUEST_BYTES`
206
+ * (128 KiB), which a value that is not a non-negative safe integer also
207
+ * falls back to.
208
+ */
209
+ maxRequestBytes?: number;
210
+ /** Name/version advertised in the MCP `initialize` handshake. Defaults to `lunora-paid-mcp`. */
211
+ serverInfo?: {
212
+ name: string;
213
+ version: string;
214
+ };
215
+ }
216
+ /**
217
+ * The Worker execution context, as this module reads it: only `waitUntil`, and
218
+ * structurally, so the package takes no `@cloudflare/workers-types` dependency.
219
+ */
220
+ interface PaidMcpExecutionContext {
221
+ waitUntil?: (promise: Promise<unknown>) => void;
222
+ }
223
+ /**
224
+ * The paid server's fetch handler.
225
+ *
226
+ * Unlike the free `McpFetchHandler` it takes the Worker's full
227
+ * `(request, env, ctx)` triple — the shape `export default { fetch }` is called
228
+ * with — because the x402 receipt sink NEEDS `ctx.waitUntil`: work that is
229
+ * neither awaited into the response nor registered with it is cancelled when the
230
+ * request ends, so an async `onReceipt` (inserting the settled payment into a
231
+ * durable table) frequently never runs while the money has already moved
232
+ * on-chain. `env` is accepted and ignored so the handler drops straight into the
233
+ * default export; both are optional, so a non-Workers caller may still invoke it
234
+ * with a bare `Request` (the middleware then simply sees no `waitUntil`).
235
+ */
236
+ type PaidMcpFetchHandler = (request: Request, env?: unknown, context?: PaidMcpExecutionContext) => Promise<Response>;
237
+ /** A paid MCP server: register free/paid tools, then serve over Streamable HTTP. */
238
+ interface PaidMcpServer {
239
+ /** The Streamable-HTTP fetch handler; gates each paid `tools/call` behind x402. */
240
+ readonly fetchHandler: PaidMcpFetchHandler;
241
+ /** Register a **paid** tool: its dispatch runs the x402 charge middleware first. */
242
+ paidTool: (options: RegisterPaidToolOptions, handler: ToolHandler) => void;
243
+ /** Register a **free** tool (coexists with paid tools on the same server). */
244
+ tool: (options: RegisterToolOptions, handler: ToolHandler) => void;
245
+ }
246
+ /**
247
+ * Create a paid MCP server. Register free tools with `tool()` and priced tools
248
+ * with `paidTool()` (they coexist), then serve `fetchHandler` over HTTP.
249
+ *
250
+ * The server is **stateless**: `fetchHandler` builds a fresh `Server` per
251
+ * request (reading the live tool registry), so tools registered before the
252
+ * first request are all visible. Each priced tool memoises one initialised
253
+ * `ChargeMiddleware` (keyed by tool name, baking that tool's price and naming
254
+ * the tool as the challenge `resource`); a failed init is not cached, so a
255
+ * transient facilitator outage retries on the next call.
256
+ */
257
+ declare const createPaidMcpServer: (config: PaidMcpServerConfig) => PaidMcpServer;
258
+ export { type AuthedMcpFetchHandlerOptions, type AuthedMcpServerOptions, type McpAccessTokenClaims, type McpAuthProtect, type McpFetchHandler, type McpFetchHandlerOptions, OBSERVABILITY_TOOL_DEFINITIONS, type PaidMcpChargeConfig, type PaidMcpExecutionContext, type PaidMcpFetchHandler, type PaidMcpServer, type PaidMcpServerConfig, READ_ONLY_TOOL_DEFINITIONS, type RegisterPaidToolOptions, type RegisterToolOptions, type ToolDefinition, type ToolHandler, type ToolInputSchema, type ToolResult, WRITE_TOOL_DEFINITIONS, callTool, createAuthedMcpFetchHandler, createMcpFetchHandler, createPaidMcpServer, mcpTokenScopes, toolDefinitions };