@lunora/mcp 1.0.0-alpha.258 → 1.0.0-alpha.259
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/README.md +48 -0
- package/dist/bin.mjs +1 -1
- package/dist/docs/index.d.mts +2 -2
- package/dist/docs/index.d.ts +2 -2
- package/dist/docs/index.mjs +1 -1
- package/dist/index.d.mts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.mjs +1 -1
- package/dist/node/index.d.mts +13 -10
- package/dist/node/index.d.ts +13 -10
- package/dist/node/index.mjs +1 -1
- package/dist/packem_shared/{AGENT_RUN_INPUT_SCHEMA-BBVvXopY.mjs → AGENT_RUN_INPUT_SCHEMA-BGbKIek4.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_SEARCH_LIMIT-DpGKT-Xt.mjs → DEFAULT_SEARCH_LIMIT-BMQ6HQ-x.mjs} +1 -1
- package/dist/packem_shared/{DOCS_SERVER_NAME-B4fL5sGF.mjs → DOCS_SERVER_NAME-ClS4cCGm.mjs} +1 -1
- package/dist/packem_shared/{DOCS_URI_SCHEME-B_C2tA0y.mjs → DOCS_URI_SCHEME-DBlxtzS6.mjs} +1 -1
- package/dist/packem_shared/{LOCAL_SERVER_NAME-3ydSaBjA.mjs → LOCAL_SERVER_NAME-BAK3cHeB.mjs} +1 -1
- package/dist/packem_shared/{OBSERVABILITY_TOOL_DEFINITIONS-DrY5Gp38.mjs → OBSERVABILITY_TOOL_DEFINITIONS-DQ7AUah0.mjs} +1 -1
- package/dist/packem_shared/READ_ONLY_TOOL_DEFINITIONS-BimWNHPm.mjs +1 -0
- package/dist/packem_shared/{compose.d-CNiBViBW.d.mts → compose.d-DiPnHeQv.d.mts} +1 -0
- package/dist/packem_shared/{compose.d-CNiBViBW.d.ts → compose.d-DiPnHeQv.d.ts} +1 -0
- package/dist/packem_shared/connectFunctionStdio-CLZ9TwNh.mjs +1 -0
- package/dist/packem_shared/{connectStdio-6IiRToo3.mjs → connectStdio-D5fO9l91.mjs} +1 -1
- package/dist/packem_shared/{createAuthedMcpFetchHandler-p0s_B8zQ.mjs → createAuthedMcpFetchHandler-CuW8wLOn.mjs} +1 -1
- package/dist/packem_shared/createFunctionMcpServer-cU_kZVAn.mjs +1 -0
- package/dist/packem_shared/createLunoraMcpServer-BkcZc2Au.mjs +1 -0
- package/dist/packem_shared/{createMcpFetchHandler-BYfzdfV-.mjs → createMcpFetchHandler-CcYLsaGa.mjs} +1 -1
- package/dist/packem_shared/{createPaidMcpServer-DQmcP8ls.mjs → createPaidMcpServer-CdDLw3G4.mjs} +1 -1
- package/dist/packem_shared/{createToolServer-Bf_IxX3S.mjs → createToolServer-CHAjfuNx.mjs} +1 -1
- package/dist/packem_shared/{server.d-C7ciln6z.d.mts → function-server.d-ByIkBRXs.d.ts} +46 -2
- package/dist/packem_shared/{server.d-CXO7cw_h.d.ts → function-server.d-D_0-WiS2.d.mts} +46 -2
- package/dist/packem_shared/package-LcPKxrnd.mjs +1 -0
- package/dist/packem_shared/tool-result-CPDsNNuJ.mjs +1 -0
- package/dist/packem_shared/tools-Bylr9LPQ.mjs +2 -0
- package/dist/worker/index.d.mts +5 -5
- package/dist/worker/index.d.ts +5 -5
- package/dist/worker/index.mjs +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/READ_ONLY_TOOL_DEFINITIONS-BEaoA4xz.mjs +0 -1
- package/dist/packem_shared/createLunoraMcpServer-DPqCfPhB.mjs +0 -1
- package/dist/packem_shared/tool-result--Yq36pE-.mjs +0 -1
- package/dist/packem_shared/tools-BrvavFhl.mjs +0 -2
package/README.md
CHANGED
|
@@ -212,6 +212,54 @@ const server = createLunoraMcpServer({ url: "https://app.example.workers.dev", t
|
|
|
212
212
|
await server.connect(myTransport);
|
|
213
213
|
```
|
|
214
214
|
|
|
215
|
+
## Expose your app's functions
|
|
216
|
+
|
|
217
|
+
`createLunoraMcpServer` fronts a deployment with generic tools (`lunora_run_query`, `lunora_run_mutation`, …). To give a model one tool per function in **your** app, with typed arguments, build the server from the OpenRPC document your app generates:
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
import { createFunctionMcpServer } from "@lunora/mcp";
|
|
221
|
+
import { openRpcSpec } from "./lunora/_generated/openrpc";
|
|
222
|
+
|
|
223
|
+
const server = createFunctionMcpServer({
|
|
224
|
+
url: env.LUNORA_URL,
|
|
225
|
+
token: caller.token, // the caller's bearer, not an admin token
|
|
226
|
+
openRpcSpec,
|
|
227
|
+
allowWrites: false,
|
|
228
|
+
});
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
For a Worker that serves MCP over HTTP, build the server per request, with the signed-in user's token, and hand it to `serveStateless`:
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
import { createFunctionMcpServer, serveStateless } from "@lunora/mcp/worker";
|
|
235
|
+
|
|
236
|
+
export default {
|
|
237
|
+
async fetch(request: Request, env: Env): Promise<Response> {
|
|
238
|
+
const user = await resolveUser(request); // your own session check
|
|
239
|
+
const server = createFunctionMcpServer({ url: env.LUNORA_URL, token: user.token, openRpcSpec });
|
|
240
|
+
|
|
241
|
+
return serveStateless(server, request);
|
|
242
|
+
},
|
|
243
|
+
};
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
Requirements and behaviour:
|
|
247
|
+
|
|
248
|
+
- **Generate the document.** Pass `apiSpec: "openrpc"` (or `"both"`) to the Vite plugin, or run `lunora codegen --api-spec openrpc`. Without it, `_generated/openrpc.ts` is not emitted and the import fails.
|
|
249
|
+
- **Identity is the caller's.** Each tool runs as `token` through the public RPC path, so auth and row-level security apply as they do in the app. Nothing calls `/_lunora/admin/*`, so no admin token is needed.
|
|
250
|
+
- **One tool per query, mutation, action and stream.** Internal functions are not listed. The tool name is the function path with non-identifier characters replaced by `_` (`billing/invoices:create` → `billing_invoices_create`). Construction throws if two functions map to one name or a name exceeds 64 characters.
|
|
251
|
+
- **Descriptions come from the doc comment** above `export const name = query(…)`. A function without one gets a generated sentence.
|
|
252
|
+
- **Writes are off by default.** With `allowWrites: false`, mutation and action tools are not listed and a direct call is refused. With it on, each write uses the same two-step confirmation as [Write confirmation](#write-confirmation-the-two-step-handshake). The digest is keyed by `token`, so writes need one. A write tool has no `outputSchema`, because its first call returns a proposal rather than the function's result.
|
|
253
|
+
- **Arguments are decoded.** A `v.bigint()` argument arrives as a decimal string and is converted back to a `bigint`; a `v.bytes()` argument arrives as base64 and is converted to an `ArrayBuffer`. A nullable or union argument is decoded through the one branch the value fits: its JSON type, its `const`, the `const` properties of an object (a discriminator), and the carrier of a string (a decimal for `v.bigint()`, canonical base64 for `v.bytes()`). A value that still fits several branches (`v.union(v.string(), v.bigint())` with `"5"`) is sent as it is, because picking one would guess. A decimal string whose length is a multiple of four is also canonical base64, so a `v.bigint()`-or-`v.bytes()` union leaves it as it is.
|
|
254
|
+
- **Results match `.output()`.** A declared object output is returned as `structuredContent` and checked against the `outputSchema`. A non-object output is wrapped as `{ result }`, because MCP requires an object root. `result` is not required in that wrapper, since a handler whose output is optional returns `undefined`, which arrives as an empty object. An object output that returns `undefined` is sent as `{}`, and its `outputSchema` admits the empty object, because the document does not say whether an output can be absent. The same schema therefore accepts `{}` for a required object output too. A function with no `.output()` has no `outputSchema`.
|
|
255
|
+
- **A changed document is announced on the next request.** `openRpcSpec` may be a function that returns the document, and it is read on each `tools/list` and `tools/call`. The tools are rebuilt, and the client is told its tool list changed, when a request finds the document different. A host that wants the change announced before any request has to make a request itself, or watch the file as `lunora mcp serve --functions` does.
|
|
256
|
+
- **A stream is a read-only tool that collects its chunks.** The call runs the stream to completion and returns every chunk, in order, as the text block, with no `outputSchema` and no wrapping. A mid-stream error is an error result. When the caller aborts, the stream is cancelled on the Lunora socket. A stream is capped at 10,000 chunks (`MAX_STREAM_CHUNKS`): the chunk past the cap cancels the stream and returns a `PAYLOAD_TOO_LARGE` error with no chunks. A stream is also capped at 16 MiB of collected chunk JSON (`MAX_STREAM_BYTES`), and the chunk past that cap cancels it the same way. Neither cap bounds the time a stream may run.
|
|
257
|
+
- **Sensitive arguments** (`v.sensitive`) are masked in a write proposal, whole argument at a time, wherever the sensitive value sits inside it. The call is sent on a reference that the client never queues offline.
|
|
258
|
+
- **The deployment URL can resolve late.** `url` may be a function, read on every call. While it returns `undefined`, a call returns `SERVICE_UNAVAILABLE` and the server keeps running. A stream cancelled by the caller returns a `CANCELLED` error, not the chunks it had.
|
|
259
|
+
- **Over stdio, for an editor:** `connectFunctionStdio(options)`, from the root entry or `@lunora/mcp/node`, builds the server and connects it to stdio. The CLI does the same with `lunora mcp serve --functions --token <your bearer>`, and it starts before `lunora dev` is running. The `--token` is the only bearer that mode uses: the project's admin token is never sent to these tools.
|
|
260
|
+
- **Stream progress** is one `notifications/progress` per chunk (the progress value is the chunk's index, with no total), sent only when the request carries a `progressToken`. It reaches the caller only over a transport that delivers notifications during the call. `serveStateless` answers each request as a single JSON body, so there the chunks still arrive in the result, but no progress does.
|
|
261
|
+
- **Not yet supported:** `shardKey` is always accepted even for an unsharded function.
|
|
262
|
+
|
|
215
263
|
## Expose an agent
|
|
216
264
|
|
|
217
265
|
A deployment's durable [`@lunora/agent`](https://www.npmjs.com/package/@lunora/agent) agents can be fronted as MCP tools. This is **opt-in and fail-closed**, mirroring `allowWrites`: starting an agent run is a side effect, so the agent tools are omitted from the advertised list _and_ refused at dispatch unless you explicitly enable them. `@lunora/mcp` takes no dependency on `@lunora/agent` — it reaches the agent's public `agents:agentRun` mutation over RPC like any other function.
|
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-
|
|
2
|
+
import{parseAgentsEnv as N}from"./packem_shared/AGENT_RUN_INPUT_SCHEMA-BGbKIek4.mjs";import l from"./packem_shared/connectStdio-D5fO9l91.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/docs/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { f as McpResourceProvider, T as ToolDefinition, a as McpTool } from "../packem_shared/compose.d-
|
|
1
|
+
import { f as McpResourceProvider, T as ToolDefinition, a as McpTool } from "../packem_shared/compose.d-DiPnHeQv.mjs";
|
|
2
2
|
export type {
|
|
3
3
|
/**
|
|
4
4
|
* `@lunora/mcp/docs` — the documentation tool surface: `lunora_search_docs`,
|
|
@@ -49,7 +49,7 @@ g as McpResourceSummary,
|
|
|
49
49
|
* (`createToolServer`) is exported from the package root, so a consumer using
|
|
50
50
|
* both entries gets one implementation rather than two copies.
|
|
51
51
|
*/
|
|
52
|
-
M as McpServerInfo, b as ToolInputSchema, d as ToolResult } from "../packem_shared/compose.d-
|
|
52
|
+
M as McpServerInfo, b as ToolInputSchema, d as ToolResult } from "../packem_shared/compose.d-DiPnHeQv.mjs";
|
|
53
53
|
import { M as McpFetchHandler } from "../packem_shared/serve-stateless.d-DD5arqFx.mjs";
|
|
54
54
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
55
55
|
import '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
|
package/dist/docs/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { f as McpResourceProvider, T as ToolDefinition, a as McpTool } from "../packem_shared/compose.d-
|
|
1
|
+
import { f as McpResourceProvider, T as ToolDefinition, a as McpTool } from "../packem_shared/compose.d-DiPnHeQv.js";
|
|
2
2
|
export type {
|
|
3
3
|
/**
|
|
4
4
|
* `@lunora/mcp/docs` — the documentation tool surface: `lunora_search_docs`,
|
|
@@ -49,7 +49,7 @@ g as McpResourceSummary,
|
|
|
49
49
|
* (`createToolServer`) is exported from the package root, so a consumer using
|
|
50
50
|
* both entries gets one implementation rather than two copies.
|
|
51
51
|
*/
|
|
52
|
-
M as McpServerInfo, b as ToolInputSchema, d as ToolResult } from "../packem_shared/compose.d-
|
|
52
|
+
M as McpServerInfo, b as ToolInputSchema, d as ToolResult } from "../packem_shared/compose.d-DiPnHeQv.js";
|
|
53
53
|
import { M as McpFetchHandler } from "../packem_shared/serve-stateless.d-DD5arqFx.js";
|
|
54
54
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
55
55
|
import '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
|
package/dist/docs/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toDocsSearchHits as e}from"../packem_shared/toDocsSearchHits-CBLmtWXt.mjs";import{DEFAULT_DOCS_BASE_URL as D,createRemoteDocsIndex as t}from"../packem_shared/DEFAULT_DOCS_BASE_URL-CiHy_Dbz.mjs";import{DOCS_URI_SCHEME as s,docsResources as S,fromDocsUri as E,toDocsUri as I}from"../packem_shared/DOCS_URI_SCHEME-
|
|
1
|
+
import{toDocsSearchHits as e}from"../packem_shared/toDocsSearchHits-CBLmtWXt.mjs";import{DEFAULT_DOCS_BASE_URL as D,createRemoteDocsIndex as t}from"../packem_shared/DEFAULT_DOCS_BASE_URL-CiHy_Dbz.mjs";import{DOCS_URI_SCHEME as s,docsResources as S,fromDocsUri as E,toDocsUri as I}from"../packem_shared/DOCS_URI_SCHEME-DBlxtzS6.mjs";import{DOCS_SERVER_NAME as R,createDocsMcpFetchHandler as p,createDocsMcpServer as A}from"../packem_shared/DOCS_SERVER_NAME-ClS4cCGm.mjs";import{DEFAULT_SEARCH_LIMIT as M,DOCS_TOOL_DEFINITIONS as O,MAX_SEARCH_LIMIT as T,docsTools as U,normalizeDocUrl as a}from"../packem_shared/DEFAULT_SEARCH_LIMIT-BMQ6HQ-x.mjs";export{D as DEFAULT_DOCS_BASE_URL,M as DEFAULT_SEARCH_LIMIT,R as DOCS_SERVER_NAME,O as DOCS_TOOL_DEFINITIONS,s as DOCS_URI_SCHEME,T as MAX_SEARCH_LIMIT,p as createDocsMcpFetchHandler,A as createDocsMcpServer,t as createRemoteDocsIndex,S as docsResources,U as docsTools,E as fromDocsUri,a as normalizeDocUrl,e as toDocsSearchHits,I as toDocsUri};
|
package/dist/index.d.mts
CHANGED
|
@@ -36,7 +36,7 @@ export { A as AGENT_RUN_INPUT_SCHEMA, a as AGENT_STATUS_TOOL_NAME,
|
|
|
36
36
|
* better-auth's MCP OAuth gate (`requireMcpAuth` from `@lunora/auth/plugins`)
|
|
37
37
|
* and can scope tool exposure to the access token's own scopes.
|
|
38
38
|
*/
|
|
39
|
-
type C as CallAgentToolOptions, type L as LunoraMcpServerOptions,
|
|
39
|
+
type C as CallAgentToolOptions, type F as FunctionMcpServerOptions, type L as LunoraMcpServerOptions,
|
|
40
40
|
/**
|
|
41
41
|
* `@lunora/mcp` — Model Context Protocol servers for Lunora. This entry exposes
|
|
42
42
|
* a *deployment* to AI agents; the `@lunora/mcp/docs` subpath exposes the
|
|
@@ -74,10 +74,10 @@ type C as CallAgentToolOptions, type L as LunoraMcpServerOptions,
|
|
|
74
74
|
* better-auth's MCP OAuth gate (`requireMcpAuth` from `@lunora/auth/plugins`)
|
|
75
75
|
* and can scope tool exposure to the access token's own scopes.
|
|
76
76
|
*/
|
|
77
|
-
type M as McpAgentExposure, b as agentToolDefinitions, c as callAgentTool, d as createLunoraMcpServer, p as parseAgentsEnv } from "./packem_shared/server.d-
|
|
77
|
+
type M as McpAgentExposure, b as agentToolDefinitions, c as callAgentTool, d as createFunctionMcpServer, e as createLunoraMcpServer, p as parseAgentsEnv } from "./packem_shared/function-server.d-D_0-WiS2.mjs";
|
|
78
78
|
export { type AuthedMcpFetchHandlerOptions, type AuthedMcpServerOptions, type McpAccessTokenClaims, type McpAuthProtect, type McpFetchHandlerOptions, OBSERVABILITY_TOOL_DEFINITIONS, type PaidMcpChargeConfig, type PaidMcpExecutionContext, type PaidMcpFetchHandler, type PaidMcpServer, type PaidMcpServerConfig, READ_ONLY_TOOL_DEFINITIONS, type RegisterPaidToolOptions, type RegisterToolOptions, type ToolHandler, WRITE_TOOL_DEFINITIONS, callTool, createAuthedMcpFetchHandler, createMcpFetchHandler, createPaidMcpServer, mcpTokenScopes, toolDefinitions } from "./worker/index.mjs";
|
|
79
|
-
export { type M as McpServerInfo, type a as McpTool, type T as ToolDefinition, type b as ToolInputSchema, type c as ToolOutputSchema, type d as ToolResult, e as createToolServer } from "./packem_shared/compose.d-
|
|
80
|
-
export { LOCAL_SERVER_NAME, type LocalDeployment, type LocalDeploymentSource, type LocalMcpServerOptions, NO_DEPLOYMENT_MESSAGE, connectLocalStdio, connectStdio, createLocalMcpServer, localTools } from "./node/index.mjs";
|
|
79
|
+
export { type M as McpServerInfo, type a as McpTool, type T as ToolDefinition, type b as ToolInputSchema, type c as ToolOutputSchema, type d as ToolResult, e as createToolServer } from "./packem_shared/compose.d-DiPnHeQv.mjs";
|
|
80
|
+
export { LOCAL_SERVER_NAME, type LocalDeployment, type LocalDeploymentSource, type LocalMcpServerOptions, NO_DEPLOYMENT_MESSAGE, connectFunctionStdio, connectLocalStdio, connectStdio, createLocalMcpServer, localTools } from "./node/index.mjs";
|
|
81
81
|
export { D as DEFAULT_MAX_REQUEST_BYTES, type M as McpFetchHandler, type S as ServeStatelessOptions, s as serveStateless } from "./packem_shared/serve-stateless.d-DD5arqFx.mjs";
|
|
82
82
|
import '@lunora/client';
|
|
83
83
|
import '@modelcontextprotocol/sdk/server/index.js';
|
package/dist/index.d.ts
CHANGED
|
@@ -36,7 +36,7 @@ export { A as AGENT_RUN_INPUT_SCHEMA, a as AGENT_STATUS_TOOL_NAME,
|
|
|
36
36
|
* better-auth's MCP OAuth gate (`requireMcpAuth` from `@lunora/auth/plugins`)
|
|
37
37
|
* and can scope tool exposure to the access token's own scopes.
|
|
38
38
|
*/
|
|
39
|
-
type C as CallAgentToolOptions, type L as LunoraMcpServerOptions,
|
|
39
|
+
type C as CallAgentToolOptions, type F as FunctionMcpServerOptions, type L as LunoraMcpServerOptions,
|
|
40
40
|
/**
|
|
41
41
|
* `@lunora/mcp` — Model Context Protocol servers for Lunora. This entry exposes
|
|
42
42
|
* a *deployment* to AI agents; the `@lunora/mcp/docs` subpath exposes the
|
|
@@ -74,10 +74,10 @@ type C as CallAgentToolOptions, type L as LunoraMcpServerOptions,
|
|
|
74
74
|
* better-auth's MCP OAuth gate (`requireMcpAuth` from `@lunora/auth/plugins`)
|
|
75
75
|
* and can scope tool exposure to the access token's own scopes.
|
|
76
76
|
*/
|
|
77
|
-
type M as McpAgentExposure, b as agentToolDefinitions, c as callAgentTool, d as createLunoraMcpServer, p as parseAgentsEnv } from "./packem_shared/server.d-
|
|
77
|
+
type M as McpAgentExposure, b as agentToolDefinitions, c as callAgentTool, d as createFunctionMcpServer, e as createLunoraMcpServer, p as parseAgentsEnv } from "./packem_shared/function-server.d-ByIkBRXs.js";
|
|
78
78
|
export { type AuthedMcpFetchHandlerOptions, type AuthedMcpServerOptions, type McpAccessTokenClaims, type McpAuthProtect, type McpFetchHandlerOptions, OBSERVABILITY_TOOL_DEFINITIONS, type PaidMcpChargeConfig, type PaidMcpExecutionContext, type PaidMcpFetchHandler, type PaidMcpServer, type PaidMcpServerConfig, READ_ONLY_TOOL_DEFINITIONS, type RegisterPaidToolOptions, type RegisterToolOptions, type ToolHandler, WRITE_TOOL_DEFINITIONS, callTool, createAuthedMcpFetchHandler, createMcpFetchHandler, createPaidMcpServer, mcpTokenScopes, toolDefinitions } from "./worker/index.js";
|
|
79
|
-
export { type M as McpServerInfo, type a as McpTool, type T as ToolDefinition, type b as ToolInputSchema, type c as ToolOutputSchema, type d as ToolResult, e as createToolServer } from "./packem_shared/compose.d-
|
|
80
|
-
export { LOCAL_SERVER_NAME, type LocalDeployment, type LocalDeploymentSource, type LocalMcpServerOptions, NO_DEPLOYMENT_MESSAGE, connectLocalStdio, connectStdio, createLocalMcpServer, localTools } from "./node/index.js";
|
|
79
|
+
export { type M as McpServerInfo, type a as McpTool, type T as ToolDefinition, type b as ToolInputSchema, type c as ToolOutputSchema, type d as ToolResult, e as createToolServer } from "./packem_shared/compose.d-DiPnHeQv.js";
|
|
80
|
+
export { LOCAL_SERVER_NAME, type LocalDeployment, type LocalDeploymentSource, type LocalMcpServerOptions, NO_DEPLOYMENT_MESSAGE, connectFunctionStdio, connectLocalStdio, connectStdio, createLocalMcpServer, localTools } from "./node/index.js";
|
|
81
81
|
export { D as DEFAULT_MAX_REQUEST_BYTES, type M as McpFetchHandler, type S as ServeStatelessOptions, s as serveStateless } from "./packem_shared/serve-stateless.d-DD5arqFx.js";
|
|
82
82
|
import '@lunora/client';
|
|
83
83
|
import '@modelcontextprotocol/sdk/server/index.js';
|
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 a,parseAgentsEnv as T}from"./packem_shared/AGENT_RUN_INPUT_SCHEMA-
|
|
1
|
+
import{AGENT_RUN_INPUT_SCHEMA as r,AGENT_STATUS_TOOL_NAME as t,agentToolDefinitions as c,callAgentTool as a,parseAgentsEnv as T}from"./packem_shared/AGENT_RUN_INPUT_SCHEMA-BGbKIek4.mjs";import{createAuthedMcpFetchHandler as p,mcpTokenScopes as E}from"./packem_shared/createAuthedMcpFetchHandler-CuW8wLOn.mjs";import{createToolServer as _}from"./packem_shared/createToolServer-CHAjfuNx.mjs";import{createFunctionMcpServer as f}from"./packem_shared/createFunctionMcpServer-cU_kZVAn.mjs";import{default as s}from"./packem_shared/connectFunctionStdio-CLZ9TwNh.mjs";import{createMcpFetchHandler as N}from"./packem_shared/createMcpFetchHandler-CcYLsaGa.mjs";import{LOCAL_SERVER_NAME as x,NO_DEPLOYMENT_MESSAGE as I,connectLocalStdio as L,createLocalMcpServer as i,localTools as M}from"./packem_shared/LOCAL_SERVER_NAME-BAK3cHeB.mjs";import{createPaidMcpServer as D}from"./packem_shared/createPaidMcpServer-CdDLw3G4.mjs";import{createLunoraMcpServer as R}from"./packem_shared/createLunoraMcpServer-BkcZc2Au.mjs";import{default as u}from"./packem_shared/connectStdio-D5fO9l91.mjs";import{R as Y,W as g,c as h,t as B}from"./packem_shared/tools-Bylr9LPQ.mjs";import{DEFAULT_MAX_REQUEST_BYTES as H,serveStateless as P}from"./packem_shared/DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{OBSERVABILITY_TOOL_DEFINITIONS as V}from"./packem_shared/OBSERVABILITY_TOOL_DEFINITIONS-DQ7AUah0.mjs";export{r as AGENT_RUN_INPUT_SCHEMA,t as AGENT_STATUS_TOOL_NAME,H as DEFAULT_MAX_REQUEST_BYTES,x as LOCAL_SERVER_NAME,I as NO_DEPLOYMENT_MESSAGE,V as OBSERVABILITY_TOOL_DEFINITIONS,Y as READ_ONLY_TOOL_DEFINITIONS,g as WRITE_TOOL_DEFINITIONS,c as agentToolDefinitions,a as callAgentTool,h as callTool,s as connectFunctionStdio,L as connectLocalStdio,u as connectStdio,p as createAuthedMcpFetchHandler,f as createFunctionMcpServer,i as createLocalMcpServer,R as createLunoraMcpServer,N as createMcpFetchHandler,D as createPaidMcpServer,_ as createToolServer,M as localTools,E as mcpTokenScopes,T as parseAgentsEnv,P as serveStateless,B as toolDefinitions};
|
package/dist/node/index.d.mts
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
|
-
import { LunoraClient } from '@lunora/client';
|
|
2
1
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
import { F as FunctionMcpServerOptions, L as LunoraMcpServerOptions } from "../packem_shared/function-server.d-D_0-WiS2.mjs";
|
|
3
|
+
export { e as createLunoraMcpServer } from "../packem_shared/function-server.d-D_0-WiS2.mjs";
|
|
4
|
+
import { LunoraClient } from '@lunora/client';
|
|
5
|
+
import { a as McpTool } from "../packem_shared/compose.d-DiPnHeQv.mjs";
|
|
6
|
+
/**
|
|
7
|
+
* Build a per-function server and connect it over stdio, the transport an editor
|
|
8
|
+
* spawns. Resolves once the transport is connected; the process then stays alive
|
|
9
|
+
* serving requests. Lives apart from `./stdio` for the same reason that module
|
|
10
|
+
* does: the Worker entry's module graph never pulls in the stdio transport.
|
|
11
|
+
*/
|
|
12
|
+
declare const connectFunctionStdio: (options: FunctionMcpServerOptions) => Promise<Server>;
|
|
6
13
|
/** A Lunora deployment the tools dispatch against. */
|
|
7
14
|
interface LocalDeployment {
|
|
8
15
|
token?: string;
|
|
@@ -81,10 +88,6 @@ declare const connectLocalStdio: (options?: LocalMcpServerOptions) => Promise<Se
|
|
|
81
88
|
* in the stdio transport (and its `node:process` import).
|
|
82
89
|
*/
|
|
83
90
|
declare const connectStdio: (options: LunoraMcpServerOptions) => Promise<Server>;
|
|
84
|
-
export { LOCAL_SERVER_NAME,
|
|
85
|
-
/** Node-only entry: the stdio transport and the local/deployment servers. */
|
|
86
|
-
type LocalDeployment,
|
|
87
|
-
/** Node-only entry: the stdio transport and the local/deployment servers. */
|
|
88
|
-
type LocalDeploymentSource,
|
|
91
|
+
export { LOCAL_SERVER_NAME, type LocalDeployment, type LocalDeploymentSource, type LocalMcpServerOptions, type LunoraMcpServerOptions, NO_DEPLOYMENT_MESSAGE,
|
|
89
92
|
/** Node-only entry: the stdio transport and the local/deployment servers. */
|
|
90
|
-
|
|
93
|
+
connectFunctionStdio, connectLocalStdio, connectStdio, createLocalMcpServer, localTools };
|
package/dist/node/index.d.ts
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
|
-
import { LunoraClient } from '@lunora/client';
|
|
2
1
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
import { F as FunctionMcpServerOptions, L as LunoraMcpServerOptions } from "../packem_shared/function-server.d-ByIkBRXs.js";
|
|
3
|
+
export { e as createLunoraMcpServer } from "../packem_shared/function-server.d-ByIkBRXs.js";
|
|
4
|
+
import { LunoraClient } from '@lunora/client';
|
|
5
|
+
import { a as McpTool } from "../packem_shared/compose.d-DiPnHeQv.js";
|
|
6
|
+
/**
|
|
7
|
+
* Build a per-function server and connect it over stdio, the transport an editor
|
|
8
|
+
* spawns. Resolves once the transport is connected; the process then stays alive
|
|
9
|
+
* serving requests. Lives apart from `./stdio` for the same reason that module
|
|
10
|
+
* does: the Worker entry's module graph never pulls in the stdio transport.
|
|
11
|
+
*/
|
|
12
|
+
declare const connectFunctionStdio: (options: FunctionMcpServerOptions) => Promise<Server>;
|
|
6
13
|
/** A Lunora deployment the tools dispatch against. */
|
|
7
14
|
interface LocalDeployment {
|
|
8
15
|
token?: string;
|
|
@@ -81,10 +88,6 @@ declare const connectLocalStdio: (options?: LocalMcpServerOptions) => Promise<Se
|
|
|
81
88
|
* in the stdio transport (and its `node:process` import).
|
|
82
89
|
*/
|
|
83
90
|
declare const connectStdio: (options: LunoraMcpServerOptions) => Promise<Server>;
|
|
84
|
-
export { LOCAL_SERVER_NAME,
|
|
85
|
-
/** Node-only entry: the stdio transport and the local/deployment servers. */
|
|
86
|
-
type LocalDeployment,
|
|
87
|
-
/** Node-only entry: the stdio transport and the local/deployment servers. */
|
|
88
|
-
type LocalDeploymentSource,
|
|
91
|
+
export { LOCAL_SERVER_NAME, type LocalDeployment, type LocalDeploymentSource, type LocalMcpServerOptions, type LunoraMcpServerOptions, NO_DEPLOYMENT_MESSAGE,
|
|
89
92
|
/** Node-only entry: the stdio transport and the local/deployment servers. */
|
|
90
|
-
|
|
93
|
+
connectFunctionStdio, connectLocalStdio, connectStdio, createLocalMcpServer, localTools };
|
package/dist/node/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LOCAL_SERVER_NAME as
|
|
1
|
+
import{default as r}from"../packem_shared/connectFunctionStdio-CLZ9TwNh.mjs";import{LOCAL_SERVER_NAME as c,NO_DEPLOYMENT_MESSAGE as a,connectLocalStdio as n,createLocalMcpServer as S,localTools as l}from"../packem_shared/LOCAL_SERVER_NAME-BAK3cHeB.mjs";import{createLunoraMcpServer as f}from"../packem_shared/createLunoraMcpServer-BkcZc2Au.mjs";import{default as L}from"../packem_shared/connectStdio-D5fO9l91.mjs";export{c as LOCAL_SERVER_NAME,a as NO_DEPLOYMENT_MESSAGE,r as connectFunctionStdio,n as connectLocalStdio,L as connectStdio,S as createLocalMcpServer,f as createLunoraMcpServer,l as localTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as u,a as O}from"./tool-result
|
|
1
|
+
import{e as u,a as O}from"./tool-result-CPDsNNuJ.mjs";const b="agents:agentRun",A="agents:agentThread",R="agents:agentMessages",p="lunora_agent_status",_=new Set(["awaiting_input","cancelled","error","idle"]),U=6e4,H=600,P={properties:{prompt:{description:"The task or message for the agent.",type:"string"},threadKey:{description:"Reuse to continue a conversation; omit to start a new thread.",type:"string"},title:{description:"Optional thread title (first run only).",type:"string"}},required:["prompt"],type:"object"},x={properties:{threadKey:{description:"The thread key returned by an agent tool call.",type:"string"}},required:["threadKey"],type:"object"},g=t=>t.toolName??`agent_${t.name}`,K=t=>{if(t===void 0)return[];const n=[];for(const e of t.split(";")){const r=e.trim();if(r.length===0)continue;const o=r.indexOf(":");if(o<=0)continue;const a=r.slice(0,o).trim(),s=r.slice(o+1).trim();a.length===0||s.length===0||n.push({description:s,name:a})}return n},D={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},G=(t,n)=>n!==!0||t.length===0?[]:[...t.map(r=>({annotations:{destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:`Run the ${r.name} agent (starts a durable run)`},description:`${r.description} Starts a durable agent run and returns its final answer.`,inputSchema:P,name:g(r)})),{annotations:{...D,title:"Check a durable agent run"},description:"Check the status of a durable agent run (and its answer if finished) by its threadKey.",inputSchema:x,name:p}],q=(t,n)=>t===p||n.some(e=>g(e)===t),I=()=>`mcp-${crypto.randomUUID()}`,d=t=>({__lunoraRef:t}),L=async t=>{await new Promise(n=>{setTimeout(n,t)})},i=t=>({content:[{text:JSON.stringify(t,void 0,2),type:"text"}]}),l=(t,n)=>{const e=t[n];return typeof e=="string"&&e.length>0?e:void 0},T=t=>{for(let n=t.length-1;n>=0;n-=1){const e=t[n],r=e?.toolCalls,o=Array.isArray(r)&&r.length>0;if(e?.role==="assistant"&&!o)return typeof e.content=="string"?e.content:""}return""},w=t=>t!==null&&typeof t=="object"&&typeof t.status=="string"?t.status:"unknown",E=async(t,n,e,r)=>{const o=await t.query(d(R),{key:n});if(e==="error"){const a=r!==null&&typeof r=="object"?r.error:void 0;return i({error:typeof a=="string"?a:"the agent run failed",status:e,threadKey:n})}return i(e==="awaiting_input"?{hint:"This run is paused on a human-in-the-loop decision: a tool approval, or a secret the owner has to supply. Answer it in the app that owns the agent; MCP cannot answer it. Poll lunora_agent_status with this threadKey afterwards.",status:e,text:T(o),threadKey:n}:{status:e,text:T(o),threadKey:n})},k=async(t,n)=>{const e=l(n,"threadKey");if(e===void 0)return u("BAD_REQUEST",'"threadKey" is required and must be a non-empty string');const r=await t.query(d(A),{key:e}),o=w(r);return _.has(o)?E(t,e,o,r):i({status:o==="unknown"?"running":o,threadKey:e})},W=async(t,n,e,r)=>{try{if(r.allowAgents!==!0)return u("FORBIDDEN",`tool "${n}" is disabled: agent tools are off. Enable them with the LUNORA_MCP_ALLOW_AGENTS env var.`);if(n===p)return await k(t,e);const o=r.exposures.find(c=>g(c)===n);if(o===void 0)return u("NOT_FOUND",`agent tool "${n}" is not exposed by this MCP server`);const a=l(e,"prompt");if(a===void 0)return u("BAD_REQUEST",'"prompt" is required and must be a non-empty string');const s=l(e,"threadKey")??I(),h=l(e,"title"),{id:N}=await t.mutation(d(b),{agent:o.name,input:a,threadKey:s,...h===void 0?{}:{title:h}}),f=r.pollIntervalMs??H,S=r.maxWaitMs??U,v=r.wait??L,M=Math.max(1,Math.ceil(S/f));for(let c=0;c<M;c+=1){const y=await t.query(d(A),{key:s}),m=w(y);if(_.has(m))return await E(t,s,m,y);await v(f)}return i({hint:"call lunora_agent_status with this threadKey to poll for the answer",runId:N,status:"running",threadKey:s})}catch(o){return O(o)}};export{P as AGENT_RUN_INPUT_SCHEMA,p as AGENT_STATUS_TOOL_NAME,G as agentToolDefinitions,W as callAgentTool,T as finalAnswer,q as isAgentToolName,K as parseAgentsEnv};
|
package/dist/packem_shared/{DEFAULT_SEARCH_LIMIT-DpGKT-Xt.mjs → DEFAULT_SEARCH_LIMIT-BMQ6HQ-x.mjs}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{LunoraError as u}from"@lunora/errors";import{e as l}from"./tool-result
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";import{e as l}from"./tool-result-CPDsNNuJ.mjs";const m=10,g=50,S="docs",i=500,E={properties:{limit:{description:`Maximum hits to return (default ${String(m)}, max ${String(g)})`,type:"number"},query:{description:'Search terms, e.g. "shardBy" or "optimistic updates"',type:"string"}},required:["query"],type:"object"},O={properties:{url:{description:'Site-relative page URL from a search hit, e.g. "/docs/sharding"',type:"string"}},required:["url"],type:"object"},T={properties:{},type:"object"},a={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},_={annotations:{...a,title:"Search the Lunora documentation"},description:"Search the Lunora documentation and return matching pages and sections. Use this before writing Lunora code (schema, queries, mutations, actions, sharding, .global(), client hooks) so the answer reflects the framework's current API rather than a guess. Follow a hit with lunora_get_doc to read the full page.",inputSchema:E,name:"lunora_search_docs"},p={annotations:{...a,title:"Read a Lunora documentation page"},description:"Return one Lunora documentation page in full, as Markdown. Takes the `url` of a lunora_search_docs hit or a lunora_list_docs entry.",inputSchema:O,name:"lunora_get_doc"},f={annotations:{...a,title:"List the Lunora documentation pages"},description:"List every Lunora documentation page with its title and description. Prefer lunora_search_docs when you know what you're looking for.",inputSchema:T,name:"lunora_list_docs"},L=[_,p,f],s=n=>({content:[{text:JSON.stringify(n,void 0,2),type:"text"}]}),d=512,h=(n,t)=>{const e=n[t];if(typeof e!="string"||e.trim().length===0)throw new u("BAD_REQUEST",`"${t}" is required and must be a non-empty string`);if(e.length>d)throw new u("BAD_REQUEST",`"${t}" must be at most ${String(d)} characters`);return e.trim()},y=n=>{const t=typeof n=="string"?Number(n):n;return typeof t!="number"||!Number.isFinite(t)?m:Math.min(g,Math.max(1,Math.floor(t)))},N=(n,t)=>{let e;try{e=decodeURIComponent(n)}catch{throw new RangeError(`"url" contains a malformed percent-escape: ${t}`)}if(e.includes("%")||e.includes("\\"))throw new RangeError(`"url" must not contain ".." or encoded segments: ${t}`);for(const o of e.split("/"))if(o===".."||o===".")throw new RangeError(`"url" must not contain ".." or encoded segments: ${t}`)},I=n=>{let t=n.trim().replaceAll("\\","/");if(t.startsWith("http://")||t.startsWith("https://")){const e=t.slice(t.indexOf("//")+2),o=e.indexOf("/");t=o===-1?"/":e.slice(o)}for(const e of["?","#"]){const o=t.indexOf(e);o!==-1&&(t=t.slice(0,o))}for(;t.endsWith("/")&&t.length>1;)t=t.slice(0,-1);return t.startsWith("/")||(t=t.startsWith("docs/")?`/${t}`:`/${S}/${t}`),N(t,n),t},D=n=>[{definition:_,handle:async t=>{const e=h(t,"query"),o=y(t.limit),c=(await n.search(e)).slice(0,o);return c.length===0?s({hits:[],note:`no documentation matched "${e}" — try fewer or more general terms, or lunora_list_docs to browse`}):s({hits:c})}},{definition:p,handle:async t=>{let e;try{e=I(h(t,"url"))}catch(r){if(r instanceof RangeError)return l("BAD_REQUEST",r.message);throw r}const o=await n.getPage(e);return o===void 0?l("NOT_FOUND",`documentation page not found: ${e}. Use lunora_search_docs or lunora_list_docs to find a valid url.`):{content:[{text:`# ${o.title} (${o.url})
|
|
2
2
|
|
|
3
3
|
${o.content}`,type:"text"}]}}},{definition:f,handle:async()=>{const t=await n.listPages();return t.length>i?s({note:`showing the first ${String(i)} of ${String(t.length)} pages — use lunora_search_docs to find the rest`,pages:t.slice(0,i)}):s(t)}}];export{m as DEFAULT_SEARCH_LIMIT,L as DOCS_TOOL_DEFINITIONS,g as MAX_SEARCH_LIMIT,D as docsTools,I as normalizeDocUrl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createToolServer as o}from"./createToolServer-
|
|
1
|
+
import{createToolServer as o}from"./createToolServer-CHAjfuNx.mjs";import{serveStateless as s}from"./DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{DEFAULT_MAX_REQUEST_BYTES as i}from"./DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{docsResources as t}from"./DOCS_URI_SCHEME-DBlxtzS6.mjs";import{docsTools as c}from"./DEFAULT_SEARCH_LIMIT-BMQ6HQ-x.mjs";const m="lunora-docs",n=e=>({name:m,version:e??"0.0.0"}),a=e=>o(n(e.version),c(e.index),t(e.index)),v=e=>r=>s(a(e),r,{maxRequestBytes:e.maxRequestBytes});export{i as DEFAULT_MAX_REQUEST_BYTES,m as DOCS_SERVER_NAME,v as createDocsMcpFetchHandler,a as createDocsMcpServer};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{normalizeDocUrl as s}from"./DEFAULT_SEARCH_LIMIT-
|
|
1
|
+
import{normalizeDocUrl as s}from"./DEFAULT_SEARCH_LIMIT-BMQ6HQ-x.mjs";const e="lunora-docs:",n=t=>`${e}${t}`,c=t=>t.startsWith(e)?t.slice(e.length):void 0,d=t=>({list:async()=>(await t.listPages()).map(o=>({...o.description===void 0?{}:{description:o.description},mimeType:"text/markdown",name:o.title,uri:n(o.url)})),read:async i=>{const o=c(i);if(o===void 0)return;const r=await t.getPage(s(o));return r===void 0?void 0:{mimeType:"text/markdown",text:`# ${r.title} (${r.url})
|
|
2
2
|
|
|
3
3
|
${r.content}`}}});export{e as DOCS_URI_SCHEME,d as docsResources,c as fromDocsUri,n as toDocsUri};
|
package/dist/packem_shared/{LOCAL_SERVER_NAME-3ydSaBjA.mjs → LOCAL_SERVER_NAME-BAK3cHeB.mjs}
RENAMED
|
@@ -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-
|
|
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-CHAjfuNx.mjs";import{createRemoteDocsIndex as h}from"./DEFAULT_DOCS_BASE_URL-CiHy_Dbz.mjs";import{docsResources as E}from"./DOCS_URI_SCHEME-DBlxtzS6.mjs";import{docsTools as R}from"./DEFAULT_SEARCH_LIMIT-BMQ6HQ-x.mjs";import{E as O,a as y,t as T,b as _,c as S}from"./tools-Bylr9LPQ.mjs";import{e as P}from"./tool-result-CPDsNNuJ.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}}),C="lunora",N="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?P("NO_DEPLOYMENT",N):S(t(s),c.name,o,n,i(s))}}))},I=()=>O.map(e=>({definition:e,handle:n=>Promise.resolve(y(e.name,n))})),k="lunora-spec:openrpc",w="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:k},{description:"The deployment's generated OpenAPI 3.1 document.",fetch:async e=>e.fetchOpenApi(),name:"OpenAPI specification",uri:w}],L=(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}}}),M=(e,n)=>{const t=[],r=l(e);return r!==void 0&&t.push(...R(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(L(e.deployment,r)),v({name:C,version:e.version??"0.0.0"},M(e,r),t.length===0?void 0:x(t))},V=async(e={})=>{const n=U(e);return await n.connect(new m),n};export{C as LOCAL_SERVER_NAME,N as NO_DEPLOYMENT_MESSAGE,w as OPENAPI_RESOURCE_URI,k as OPENRPC_RESOURCE_URI,V as connectLocalStdio,U as createLocalMcpServer,M as localTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as A}from"@lunora/errors";import{ADMIN_FUNCTIONS as d}from"@lunora/shard-engine";import{w as p,o as l}from"./tool-result
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{ADMIN_FUNCTIONS as d}from"@lunora/shard-engine";import{w as p,o as l}from"./tool-result-CPDsNNuJ.mjs";const u={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},I=50,b=500,v=["1m","5m","15m","1h"],w=["open","resolved","ignored"],E=["trace","debug","log","info","warn","error","fatal"],g={description:"Shard to read from on a .shardBy()-partitioned deployment. Omit for the default (unsharded) shard — these reads are PER-SHARD, not deployment-wide.",type:"string"},y={description:`Maximum rows to return (default ${I.toString()}, clamped to ${b.toString()}).`,type:"number"},O=e=>{const r=typeof e=="number"?e:Number.NaN;return Number.isFinite(r)?Math.max(1,Math.min(Math.floor(r),b)):I},_=(e,r)=>r.includes(e)?e:void 0,T=e=>typeof e=="string"&&e.length>0?e:void 0,N={properties:{level:{description:`Keep only entries at this severity. One of: ${E.join(", ")}.`,type:"string"},limit:y,shardKey:g},type:"object"},R={properties:{functionPathPrefix:{description:'Keep only Issues whose function path starts with this, e.g. "messages:".',type:"string"},limit:y,shardKey:g,status:{description:`Triage status to keep. One of: ${w.join(", ")}. Default: all.`,type:"string"}},type:"object"},P={properties:{limit:y,shardKey:g},type:"object"},U={properties:{limit:y,range:{description:`Time window to report over. One of: ${v.join(", ")}. Default: 15m.`,type:"string"},shardKey:g},type:"object"},L={properties:{shardKey:g},type:"object"},M={properties:{dropped:{description:"Entries the shard's in-memory ring EVICTED before this read — they are gone and cannot be fetched. Non-zero means `entries` + `total` describe only the newest slice of what the deployment logged.",type:"number"},entries:{description:"Recent log entries, NEWEST FIRST: { level, message, timestamp, functionPath?, fields? }.",type:"array"},total:{description:"Entries still in the ring matching `level`, before `limit` narrowed them. NOT the number of lines logged — see `dropped`.",type:"number"}},required:["dropped","entries","total"],type:"object"},H={properties:{issues:{description:"Grouped error Issues, newest first: { hash, title, count, status, functionPath, lastSeen, … }.",type:"array"}},required:["issues"],type:"object"},k={properties:{advisories:{description:"Schema/query advisories: { id, level, title, detail, … }.",type:"array"},total:{description:"Advisories available before `limit` narrowed them.",type:"number"}},required:["advisories","total"],type:"object"},j={properties:{buckets:{description:"Combined throughput/latency series across the range.",type:"array"},capped:{description:"True when the deployment's tracked-statement cap was reached, so coverage is partial.",type:"boolean"},entries:{description:"Per-statement activity in the range, hottest first.",type:"array"},total:{description:"Statements available before `limit` narrowed them.",type:"number"},trackedStatements:{description:"Distinct statements the deployment is tracking.",type:"number"}},required:["entries","buckets"],type:"object"},q={properties:{migrations:{description:"Every declared migration with its applied/pending state.",type:"array"}},required:["migrations"],type:"object"},C=[{annotations:{...u,title:"Read recent logs"},description:"Read the deployment's recent log entries (newest first) after running a function, to see what it printed and where it failed. In-memory and per-shard: resets when the shard hibernates.",inputSchema:N,name:"lunora_get_logs",outputSchema:p(M)},{annotations:{...u,title:"List grouped error Issues"},description:"List errors grouped into Issues by fingerprint, with occurrence counts and triage status — the first call when asking what is currently broken, rather than reading raw logs.",inputSchema:R,name:"lunora_get_issues",outputSchema:p(H)},{annotations:{...u,title:"List schema and query advisories"},description:"List the deployment's schema/query advisories (missing indexes, unsafe policies, and similar lints) before or after changing the schema.",inputSchema:P,name:"lunora_get_advisories",outputSchema:p(k)},{annotations:{...u,title:"Read query insights"},description:"Read per-statement execution counts and latency over a recent time window, to find which query is slow or hot before optimizing one.",inputSchema:U,name:"lunora_get_query_insights",outputSchema:p(j)},{annotations:{...u,title:"Read migration status"},description:"Read which migrations have been applied and which are pending, to check whether a schema change has actually landed on the deployment.",inputSchema:L,name:"lunora_get_migration_status",outputSchema:p(q)}],K=new Set(C.map(e=>e.name)),h=async(e,r,s,n)=>{const a={__lunoraRef:r};return e.query(a,s,{...n===void 0?{}:{shardKey:n}})},m=(e,r)=>{const s=e?.[r];return Array.isArray(s)?s:[]},V=async(e,r,s)=>{const n=T(s.shardKey),a=O(s.limit);switch(r){case"lunora_get_advisories":{const t=await h(e,d.getAdvisories,{},n),i=m(t,"advisories");return l({advisories:i.slice(0,a),total:i.length})}case"lunora_get_issues":{const t=_(s.status,w),i=T(s.functionPathPrefix),o=await h(e,d.getIssues,{limit:a,...t===void 0?{}:{status:t},...i===void 0?{}:{functionPathPrefix:i}},n);return l({issues:m(o,"issues")})}case"lunora_get_logs":{const t=_(s.level,E),i=await h(e,d.getLogs,{},n),o=m(i,"entries").filter(S=>t===void 0||S.level===t),{dropped:c}=i??{};return l({dropped:typeof c=="number"?c:0,entries:o.slice(0,a),total:o.length})}case"lunora_get_migration_status":{const t=await h(e,d.migrationStatus,{},n);return l({migrations:m(t,"migrations")})}case"lunora_get_query_insights":{const t=_(s.range,v),i=await h(e,d.getQueryInsights,{...t===void 0?{}:{range:t}},n),o=m(i,"entries"),{buckets:c,capped:S,trackedStatements:f}=i??{};return l({buckets:Array.isArray(c)?c:[],capped:S===!0,entries:o.slice(0,a),total:o.length,trackedStatements:typeof f=="number"?f:o.length})}default:throw new A("INTERNAL",`unknown observability tool: ${r}`)}};export{I as DEFAULT_LIMIT,b as MAX_LIMIT,C as OBSERVABILITY_TOOL_DEFINITIONS,K as OBSERVABILITY_TOOL_NAMES,V as callObservabilityTool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{D as E,O as _,R as s,h as a,S as o,W as S,d as D,c as A,r as N,s as r,t as R}from"./tools-Bylr9LPQ.mjs";import{OBSERVABILITY_TOOL_DEFINITIONS as t}from"./OBSERVABILITY_TOOL_DEFINITIONS-DQ7AUah0.mjs";import"./tool-result-CPDsNNuJ.mjs";export{E as DATA_READ_SCOPE,_ as OBSERVABILITY_SCOPE,t as OBSERVABILITY_TOOL_DEFINITIONS,s as READ_ONLY_TOOL_DEFINITIONS,a as ROW_READ_TOOL_DEFINITIONS,o as SCOPED_GATES,S as WRITE_TOOL_DEFINITIONS,D as WRITE_TOOL_NAMES,A as callTool,N as readArgumentsBag,r as scopeForTool,R as toolDefinitions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{StdioServerTransport as e}from"@modelcontextprotocol/sdk/server/stdio.js";import{createFunctionMcpServer as n}from"./createFunctionMcpServer-cU_kZVAn.mjs";const a=async t=>{const r=n(t);return await r.connect(new e),r};export{a as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{StdioServerTransport as i}from"@modelcontextprotocol/sdk/server/stdio.js";import{readFileSync as a}from"node:fs";import{dirname as n,join as c}from"node:path";import{fileURLToPath as s}from"node:url";import{createLunoraMcpServer as m}from"./createLunoraMcpServer-
|
|
1
|
+
import{StdioServerTransport as i}from"@modelcontextprotocol/sdk/server/stdio.js";import{readFileSync as a}from"node:fs";import{dirname as n,join as c}from"node:path";import{fileURLToPath as s}from"node:url";import{createLunoraMcpServer as m}from"./createLunoraMcpServer-BkcZc2Au.mjs";const p=()=>{let r=n(s(import.meta.url));for(let e=0;e<8;e+=1){try{const o=JSON.parse(a(c(r,"package.json"),"utf8"));if(o.name==="@lunora/mcp"&&typeof o.version=="string"&&o.version.length>0)return o.version}catch{}const t=n(r);if(t===r)break;r=t}},S=async r=>{const e=p(),t=m(e===void 0?r:{version:e,...r});return await t.connect(new i),t};export{S as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";import{isAgentToolName as S}from"./AGENT_RUN_INPUT_SCHEMA-
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{isAgentToolName as S}from"./AGENT_RUN_INPUT_SCHEMA-BGbKIek4.mjs";import{readScreenedBody as g,serveStateless as w}from"./DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{resolveClient as d,createLunoraMcpServer as T}from"./createLunoraMcpServer-BkcZc2Au.mjs";import{c as M}from"./tool-call-Bs-QeKp6.mjs";import{d as E,s as _,S as k}from"./tools-Bylr9LPQ.mjs";const A=t=>typeof t.scope!="string"?new Set:new Set(t.scope.split(" ").filter(c=>c!=="")),C=(t,c)=>{const o={...t};for(const{flag:s,scope:n}of k)o[s]=t[s]===!0&&c.has(n);return o},I=(t,c,o)=>{const s=new Set,n=c.agents??[];for(const l of t){const e=M(l);if(e===void 0)continue;(E.has(e)||S(e,n))&&s.add(o);const r=_(e,c);r!==void 0&&s.add(r)}return s},N=256,B=t=>{const{maxRequestBytes:c,stepUp:o}=t;if(o!==void 0&&(typeof o.scope!="string"||o.scope===""||typeof o.challenge!="function"))throw new y("MCP_STEP_UP_MISCONFIGURED","createAuthedMcpFetchHandler: `stepUp` needs a non-empty `scope` and a `challenge` function.");const s=typeof t.server=="function"?void 0:d(t.server),n=new Map,l=e=>{if(e.client!==void 0||e.url===void 0||e.token===void 0||e.token.length===0)return d(e);const r=JSON.stringify([e.url,e.token]),i=n.get(r);if(i!==void 0&&i.fetch===e.fetch)return n.delete(r),n.set(r,i),i.client;const f=d(e);return n.delete(r),n.set(r,{client:f,fetch:e.fetch}),n.size>N&&n.delete(n.keys().next().value),f};return t.protect(async(e,r)=>{const i=A(r),f=typeof t.server=="function"?await t.server(r):{...t.server,client:s};let a;if(o!==void 0){const p=await g(e,c);if("response"in p)return p.response;({parsedBody:a}=p);const m=Array.isArray(a)?a:[a],u=[...I(m,f,o.scope)].filter(v=>!i.has(v));if(u.length>0)throw o.challenge(u)}const h=C(typeof t.server=="function"?{...f,client:l(f)}:f,i);return await w(T(h),e,{maxRequestBytes:c,parsedBody:a})})};export{B as createAuthedMcpFetchHandler,A as mcpTokenScopes};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraClient as M}from"@lunora/client";import{Server as P}from"@modelcontextprotocol/sdk/server/index.js";import{ListToolsRequestSchema as B,CallToolRequestSchema as H}from"@modelcontextprotocol/sdk/types.js";import{p as W}from"./package-LcPKxrnd.mjs";import{LunoraError as A}from"@lunora/errors";import{f as q,w as F,e as g,a as C,b as R,o as N,j as K}from"./tool-result-CPDsNNuJ.mjs";import{e as U,r as Y,f as G,g as Q}from"./tools-Bylr9LPQ.mjs";const l=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),L=/^-?\d+$/,$=1024,J=(t,e,r)=>{const{contentEncoding:n,format:o}=t;if(o==="int64"){if(!L.test(e)||e.length>$)throw new A("BAD_REQUEST",`"${r}" must be a decimal integer string of at most ${String($)} digits`);return BigInt(e)}if(n==="base64")try{return q(e).buffer}catch{throw new A("BAD_REQUEST",`"${r}" must be base64`)}return e},V=(t,e)=>{const{type:r}=t;return typeof r!="string"?!0:r==="integer"||r==="number"?typeof e=="number":r==="array"?Array.isArray(e):r==="object"?l(e):r===typeof e},X=/^(?:[\dA-Z+/]{4})*(?:[\dA-Z+/]{2}==|[\dA-Z+/]{3}=)?$/i,Z=(t,e)=>t.format==="int64"&&!L.test(e)?!1:t.contentEncoding!=="base64"||X.test(e),x=(t,e)=>Object.entries(t).every(([r,n])=>!l(n)||!Object.hasOwn(n,"const")||!Object.hasOwn(e,r)?!0:e[r]===n.const),z=(t,e)=>!V(t,e)||Object.hasOwn(t,"const")&&t.const!==e||l(e)&&l(t.properties)&&!x(t.properties,e)?!1:typeof e!="string"||Z(t,e),tt=(t,e)=>{const r=t.filter(n=>l(n)&&z(n,e));return r.length===1?r[0]:void 0},et=(t,e)=>{const{additionalProperties:r,properties:n}=t,o=l(n)&&Object.hasOwn(n,e)?n[e]:r;return l(o)?o:void 0},S=(t,e,r)=>{const{anyOf:n,items:o}=t;if(e===null)return e;if(Array.isArray(n)){const a=tt(n,e);return a===void 0?e:S(a,e,r)}return typeof e=="string"?J(t,e,r):Array.isArray(e)&&l(o)?e.map((a,c)=>S(o,a,`${r}[${c.toString()}]`)):l(e)?Object.fromEntries(Object.entries(e).map(([a,c])=>{const s=et(t,a);return[a,s===void 0?c:S(s,c,`${r}.${a}`)]})):e},O=(t,e)=>S(t,e,"args"),T=t=>t==="action"||t==="mutation",rt=t=>t==="query"||t==="mutation"||t==="action"||t==="stream",k=64,nt=/[^\w-]/g,ot={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},st={destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1},it={description:"Shard key. Only for a function partitioned with .shardBy(); omit it otherwise.",type:"string"},ct="The first call only proposes the write. Confirm it with confirmed: true and the actionDigest the proposal returns.",at={action:t=>`Runs the action "${t}", which may call external services.`,mutation:t=>`Runs the mutation "${t}", which changes data.`,query:t=>`Runs the query "${t}". Read-only.`,stream:t=>`Runs the stream "${t}", which yields chunks. The result is every chunk, in order. Read-only.`},dt=(t,e)=>{const r=t.description??at[t.kind](t.path);return e?`${r} ${ct}`:r},b=()=>new A("BAD_REQUEST","openRpcSpec must be the OpenRPC document codegen emits (the `openRpcSpec` export of `_generated/openrpc`)"),lt=t=>t.replaceAll(nt,"_"),_=t=>Array.isArray(t)?t.some(e=>_(e)):l(t)&&(t.writeOnly===!0||Object.values(t).some(e=>_(e))),ut=t=>{const{properties:e}=t;return l(e)?Object.entries(e).filter(([,r])=>_(r)).map(([r])=>r):[]},ft=t=>{const e=l(t)&&l(t.schema)?t.schema:void 0,r=e!==void 0&&Object.hasOwn(e,"description")&&Object.keys(e).every(n=>n==="description");return e===void 0||r?{mode:"none"}:e.type==="object"?{mode:"object",schema:{...e,type:"object"}}:{mode:"wrapped",schema:{properties:{result:e},type:"object"}}},mt=t=>{const{params:e}=t,r=Array.isArray(e)?e.find(o=>l(o)&&o.name==="args"):void 0,n=l(r)?r.schema:void 0;return l(n)?n:{properties:{},type:"object"}},ht=t=>{if(!l(t))throw b();const{name:e}=t;if(typeof e!="string")throw b();const r=t["x-lunora-function-kind"];if(!rt(r))return;const n=t["x-lunora-description"];return{argsSchema:mt(t),...typeof n=="string"?{description:n}:{},kind:r,output:r==="stream"?{mode:"none"}:ft(t.result),path:e}},pt=(t,e)=>{const r=lt(t);if(r.length>k)throw new A("BAD_REQUEST",`the MCP tool name for "${t}" is ${r.length.toString()} characters; the limit is ${k.toString()}. Rename the function.`);const n=e.get(r);if(n!==void 0)throw new A("BAD_REQUEST",`"${t}" and "${n}" both map to the MCP tool name "${r}". Rename one of them.`);return e.set(r,t),r},gt=t=>{const{required:e}=t.argsSchema;return Array.isArray(e)&&e.length>0},yt=(t,e)=>({properties:{args:t.argsSchema,shardKey:it,...e?U:{}},required:gt(t)?["args"]:[],type:"object"}),At={additionalProperties:!1,properties:{},type:"object"},St=t=>{if(t.mode==="none")return;const e=F(t.schema);return t.mode==="object"?{...e,anyOf:[...e.anyOf??[],At]}:e},Ot=(t,e)=>{const r=T(e.kind),n=`${e.kind} ${e.path}`,o=r?void 0:St(e.output);return{annotations:r?{...st,title:n}:{...ot,title:n},description:dt(e,r),inputSchema:yt(e,r),name:t,...o===void 0?{}:{outputSchema:o}}},wt=t=>({argsSchema:t.argsSchema,kind:t.kind,outputMode:t.output.mode,path:t.path,sensitiveArgs:ut(t.argsSchema)}),Et=(t,e)=>{const r=l(t)?t.methods:void 0;if(!Array.isArray(r))throw b();const n=[],o=new Map,a=new Map;for(const c of r){const s=ht(c);if(s===void 0)continue;const i=pt(s.path,a);o.set(i,wt(s)),(!T(s.kind)||e.allowWrites)&&n.push(Ot(i,s))}return{definitions:n,routes:o}},Rt="lunora",j=t=>({__lunoraRef:t}),bt=t=>typeof t.shardKey=="string"&&t.shardKey.length>0?t.shardKey:void 0,D=(t,e)=>t.outputMode==="object"?e===void 0?{...R(e),structuredContent:{}}:N(e):t.outputMode==="wrapped"?N({result:e}):R(e),_t=async(t,e,r,n,o,a,c)=>{const s=e.kind==="action"?"action":"mutation";O(e.argsSchema,o);const i=G(n),f=await Q(t,{args:o,functionPath:e.path,idempotencyKey:i.idempotencyKey,kind:s,shardKey:a,tool:r},i,e.sensitiveArgs,["args","shardKey","idempotencyKey"]);if(f!==void 0)return f;const d=O(e.argsSchema,o),u=e.sensitiveArgs.length===0?j(e.path):{__lunoraRef:e.path,sensitive:!0},m=s==="action"?await t.action(u,d,{shardKey:a,signal:c}):await t.mutation(u,d,{onlineOnly:!0,shardKey:a,signal:c});return D(e,m)},E=1e4,v=16*1024*1024,Tt=async(t,e,r,n,o)=>{const a={__lunoraRef:e.path},c=t.stream(a,r,{maxBuffer:E+1,shardKey:n}),{signal:s,progress:i}=o,f=()=>{c.cancel()};s?.addEventListener("abort",f,{once:!0}),s?.aborted===!0&&f();const d=[];let u=0,m=Promise.resolve(),p;const w=(h,y)=>{m=m.then(()=>p===void 0?i?.(h,y):void 0).catch(I=>{p={error:I},c.cancel()})};try{for await(const h of c){if(d.length===E)return c.cancel(),g("PAYLOAD_TOO_LARGE",`the stream "${e.path}" yielded more than ${E.toString()} chunks, so it was cancelled and no chunks are returned.`);const y=h===void 0?"null":JSON.stringify(h,K);if(u+=y.length,u>v)return c.cancel(),g("PAYLOAD_TOO_LARGE",`the stream "${e.path}" yielded more than ${v.toString()} characters of JSON, so it was cancelled and no chunks are returned.`);d.push(h),i!==void 0&&w(d.length-1,y)}}finally{s?.removeEventListener("abort",f)}if(await m,p!==void 0)throw p.error;return s?.aborted===!0?g("CANCELLED",`the stream "${e.path}" was cancelled before it completed, after ${d.length.toString()} chunk(s).`):R(d)},Nt=async(t,e,r,n,o,a={})=>{const c=e.get(r);if(c===void 0)return g("NOT_FOUND",`unknown tool: ${r}`);if(T(c.kind)&&!o)return g("FORBIDDEN",`tool "${r}" is disabled: this MCP server is read-only. Enable writes with allowWrites.`);try{const s=Y(n.args),i=bt(n);return c.kind==="query"?D(c,await t.query(j(c.path),O(c.argsSchema,s),{shardKey:i,signal:a.signal})):c.kind==="stream"?await Tt(t,c,O(c.argsSchema,s),i,a):await _t(t,c,r,n,s,i,a.signal)}catch(s){return a.signal?.aborted===!0?g("CANCELLED",`the call to "${r}" was cancelled before it completed. A write already sent is not undone.`):C(s)}},$t=t=>{let e;const r=new Set,n=i=>{i.calls===0&&r.delete(i)&&i.client.close()},o=i=>{r.add(i),n(i)},a=()=>{e!==void 0&&(o(e),e=void 0)};return{acquire:()=>{const i=typeof t.url=="function"?t.url():t.url;if(i===void 0||i.length===0){a();return}if(e?.url!==i){a();const u=new M({fetch:t.fetch,url:i,WebSocket:t.WebSocket});t.token!==void 0&&(u.setAuthToken(t.token),u.setWsToken(t.token)),e={calls:0,client:u,url:i}}const f=e;f.calls+=1;let d=!0;return{client:f.client,done:()=>{d&&(d=!1,f.calls-=1,n(f))}}},release:()=>{a();for(const i of r)r.delete(i),i.client.close()}}},Mt=t=>{const e=t.allowWrites??!1,r=()=>typeof t.openRpcSpec=="function"?t.openRpcSpec():t.openRpcSpec,n=d=>({spec:d,tools:Et(d,{allowWrites:e})});let o=n(r());const{acquire:a,release:c}=$t(t),s=new P({name:t.name??Rt,version:t.version??W.version},{capabilities:{tools:{listChanged:!0}}}),i=()=>{let d;try{d=r()}catch(u){return t.onReloadError?.(u),o.tools}if(d!==o.spec)try{o=n(d),s.sendToolListChanged().catch(()=>{})}catch(u){t.onReloadError?.(u),o={spec:d,tools:o.tools}}return o.tools},f=s.close.bind(s);return s.close=async()=>{c(),await f()},s.setRequestHandler(B,()=>({tools:[...i().definitions]})),s.setRequestHandler(H,async(d,u)=>{let m;try{m=a()}catch(h){return C(h)}if(m===void 0)return g("SERVICE_UNAVAILABLE","no Lunora deployment URL is available yet. Start `lunora dev` or set the deployment URL, then call the tool again.");const{progressToken:p}=u._meta??{},w={signal:u.signal,...p===void 0?{}:{progress:async(h,y)=>{await u.sendNotification({method:"notifications/progress",params:{message:y,progress:h,progressToken:p}})}}};try{return await Nt(m.client,i().routes,d.params.name,d.params.arguments??{},e,w)}finally{m.done()}}),s};export{E as MAX_STREAM_CHUNKS,Nt as callFunctionTool,Mt as createFunctionMcpServer};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraClient as g}from"@lunora/client";import{LunoraError as m}from"@lunora/errors";import{Server as w}from"@modelcontextprotocol/sdk/server/index.js";import{ListToolsRequestSchema as d,CallToolRequestSchema as h}from"@modelcontextprotocol/sdk/types.js";import{p as A}from"./package-LcPKxrnd.mjs";import{agentToolDefinitions as M,isAgentToolName as T,callAgentTool as R}from"./AGENT_RUN_INPUT_SCHEMA-BGbKIek4.mjs";import{t as k,c as N}from"./tools-Bylr9LPQ.mjs";const E="lunora",L=e=>{if(e.client!==void 0)return e.client;if(e.url===void 0)throw new m("INTERNAL","createLunoraMcpServer requires either a `client` or a `url`");if(e.token===void 0||e.token.length===0)throw new m("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 t=new g({fetch:e.fetch,url:e.url});return t.setAuthToken(e.token),t},C=e=>{const t=L(e),n=e.allowWrites??!1,o=e.allowAgents??!1,r=e.agents??[],s=typeof e.token=="string"&&e.token.length>0,i=e.allowObservability===!0&&s,c=e.allowDataReads===!0&&s,a=new w({name:E,version:e.version??A.version},{capabilities:{tools:{}}});return a.setRequestHandler(d,()=>({tools:[...k(n,i,c),...M(r,o)]})),a.setRequestHandler(h,async v=>{const{arguments:f,name:l}=v.params,u=f??{};return T(l,r)?await R(t,l,u,{allowAgents:o,exposures:r,...e.agentMaxWaitMs===void 0?{}:{maxWaitMs:e.agentMaxWaitMs},...e.agentPollIntervalMs===void 0?{}:{pollIntervalMs:e.agentPollIntervalMs}}):await N(t,l,u,n,i,c)}),a};export{C as createLunoraMcpServer,L as resolveClient};
|
package/dist/packem_shared/{createMcpFetchHandler-BYfzdfV-.mjs → createMcpFetchHandler-CcYLsaGa.mjs}
RENAMED
|
@@ -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"./createLunoraMcpServer-
|
|
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"./createLunoraMcpServer-BkcZc2Au.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};
|
package/dist/packem_shared/{createPaidMcpServer-DQmcP8ls.mjs → createPaidMcpServer-CdDLw3G4.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as B}from"@lunora/errors";import{Server as E}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as M,ListToolsRequestSchema as P}from"@modelcontextprotocol/sdk/types.js";import{CfWorkerJsonSchemaValidator as _}from"@modelcontextprotocol/sdk/validation/cfworker";import{m as b}from"./promise-memo-OqVPWoUX.mjs";import{readScreenedBody as x,serveStateless as A}from"./DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{c as S}from"./tool-call-Bs-QeKp6.mjs";import{e as C,a as F}from"./tool-result
|
|
1
|
+
import{LunoraError as B}from"@lunora/errors";import{Server as E}from"@modelcontextprotocol/sdk/server/index.js";import{CallToolRequestSchema as M,ListToolsRequestSchema as P}from"@modelcontextprotocol/sdk/types.js";import{CfWorkerJsonSchemaValidator as _}from"@modelcontextprotocol/sdk/validation/cfworker";import{m as b}from"./promise-memo-OqVPWoUX.mjs";import{readScreenedBody as x,serveStateless as A}from"./DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{c as S}from"./tool-call-Bs-QeKp6.mjs";import{e as C,a as F}from"./tool-result-CPDsNNuJ.mjs";let T;const H=()=>(T??=new _,T),N=(t,o,s)=>{const d=t.validate(s);return d.valid?void 0:C("BAD_REQUEST",`invalid arguments for tool "${o}": ${d.errorMessage}`)},V=async()=>{try{return(await import("@lunora/x402/charge")).createChargeMiddleware}catch(t){throw new B("INTERNAL",`paid MCP tools need the optional peer "@lunora/x402" — install it alongside @lunora/mcp to charge for tools (${t instanceof Error?t.message:String(t)})`)}},$={name:"lunora-paid-mcp",version:"0.0.0"},q=()=>Response.json({error:"A JSON-RPC batch may not reference a paid MCP tool; send paid tools/call requests individually."},{status:400}),D=async(t,o,s,d,u)=>{const l={reached:!1},p=new E({name:"lunora-paid-mcp-preflight",version:"0.0.0"},{capabilities:{tools:{}}});p.setRequestHandler(M,v=>{const f=N(d,s,v.params.arguments??{});return l.reached=f===void 0&&v.params.name===s,f??{content:[]}});const h=await A(p,t,{maxRequestBytes:u,parsedBody:o});return l.reached?void 0:h},K=t=>{const o=new Map,s=new Map,d=new Map,u=t.serverInfo??$,l=(e,r,a)=>{if(o.has(e.name))throw new B("BAD_REQUEST",`MCP tool "${e.name}" is already registered.`);const n={annotations:e.annotations,description:e.description,inputSchema:e.inputSchema,name:e.name};o.set(e.name,{definition:n,handler:r,validate:H().getValidator(n.inputSchema)}),a!==void 0&&s.set(e.name,a)},p=()=>{const e=new E(u,{capabilities:{tools:{}}});return e.setRequestHandler(P,()=>({tools:[...o.values()].map(r=>r.definition)})),e.setRequestHandler(M,async r=>{const a=o.get(r.params.name);if(a===void 0)return C("NOT_FOUND",`unknown tool: ${r.params.name}`);const n=r.params.arguments??{},i=N(a,r.params.name,n);if(i!==void 0)return i;try{return await a.handler(n)}catch(m){return F(m)}}),e},h=(e,r)=>b(d,e,async()=>(await V())({...t.charge,price:r},{resource:e}));return{fetchHandler:async(e,r,a)=>{const n=await x(e.clone(),t.maxRequestBytes);if("response"in n)return n.response;const{parsedBody:i}=n,m=()=>A(p(),e,{maxRequestBytes:t.maxRequestBytes,parsedBody:i});if(Array.isArray(i))return i.some(w=>s.has(S(w)??""))?q():m();const c=S(i),y=c===void 0?void 0:s.get(c),R=c===void 0?void 0:o.get(c);if(c===void 0||y===void 0||R===void 0)return m();const g=await D(e,i,c,R,t.maxRequestBytes);if(g!==void 0)return g;const U=await h(c,y),j=typeof a?.waitUntil=="function"?{waitUntil:w=>{a.waitUntil?.(w)}}:void 0;return U.handle(e,m,j)},paidTool:(e,r)=>{l(e,r,e.price)},tool:(e,r)=>{l(e,r)}}};export{K as createPaidMcpServer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Server as l}from"@modelcontextprotocol/sdk/server/index.js";import{ListToolsRequestSchema as p,CallToolRequestSchema as h,ListResourcesRequestSchema as d,ReadResourceRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{w as R,e as f,a as S}from"./tool-result
|
|
1
|
+
import{Server as l}from"@modelcontextprotocol/sdk/server/index.js";import{ListToolsRequestSchema as p,CallToolRequestSchema as h,ListResourcesRequestSchema as d,ReadResourceRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{w as R,e as f,a as S}from"./tool-result-CPDsNNuJ.mjs";const y=(u,c,s)=>{const a=new Map;for(const e of c)a.has(e.definition.name)||a.set(e.definition.name,e);const i=[...a.values()].map(({definition:e})=>e.outputSchema===void 0?e:{...e,outputSchema:R(e.outputSchema)}),r=new l(u,{capabilities:s===void 0?{tools:{}}:{resources:{},tools:{}}});return r.setRequestHandler(p,()=>({tools:i})),r.setRequestHandler(h,async e=>{const{arguments:o,name:t}=e.params,n=a.get(t);if(n===void 0)return f("NOT_FOUND",`unknown tool: ${t}`);try{return await n.handle(o??{})}catch(m){return S(m)}}),s!==void 0&&(r.setRequestHandler(d,async()=>({resources:[...await s.list()]})),r.setRequestHandler(w,async e=>{const{uri:o}=e.params,t=await s.read(o);if(t===void 0)throw new Error(`unknown resource: ${o}`);return{contents:[{mimeType:t.mimeType??"text/plain",text:t.text,uri:o}]}})),r};export{y as createToolServer};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { LunoraClient } from '@lunora/client';
|
|
2
2
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
3
|
-
import { b as ToolInputSchema, T as ToolDefinition, d as ToolResult } from "./compose.d-
|
|
3
|
+
import { b as ToolInputSchema, T as ToolDefinition, d as ToolResult } from "./compose.d-DiPnHeQv.js";
|
|
4
4
|
/**
|
|
5
5
|
* Agent exposure for the MCP server: a durable `@lunora/agent` run fronted as an
|
|
6
6
|
* MCP tool an external agent can call. The capability boundary is the MCP-server
|
|
@@ -149,4 +149,48 @@ interface LunoraMcpServerOptions {
|
|
|
149
149
|
* safe to run as a short-lived stdio process.
|
|
150
150
|
*/
|
|
151
151
|
declare const createLunoraMcpServer: (options: LunoraMcpServerOptions) => Server;
|
|
152
|
-
|
|
152
|
+
interface FunctionMcpServerOptions {
|
|
153
|
+
/**
|
|
154
|
+
* Advertise and allow mutation and action tools. Off by default. A closed write
|
|
155
|
+
* is not listed and is refused at dispatch.
|
|
156
|
+
*/
|
|
157
|
+
allowWrites?: boolean;
|
|
158
|
+
fetch?: typeof fetch;
|
|
159
|
+
/** The MCP server name clients show. Defaults to `lunora`. */
|
|
160
|
+
name?: string;
|
|
161
|
+
/**
|
|
162
|
+
* Told when a rewritten document cannot be read or built. The server keeps the tools it
|
|
163
|
+
* last built, so the error is reported here rather than failing the request.
|
|
164
|
+
*/
|
|
165
|
+
onReloadError?: (error: unknown) => void;
|
|
166
|
+
/**
|
|
167
|
+
* The `openRpcSpec` export of `_generated/openrpc`, or a function returning it. A
|
|
168
|
+
* function is called on every `tools/list` and `tools/call`, so the tools follow a
|
|
169
|
+
* document that codegen rewrites while the server runs. Return the same object
|
|
170
|
+
* while the document is unchanged: a different object rebuilds the tools.
|
|
171
|
+
*/
|
|
172
|
+
openRpcSpec: unknown;
|
|
173
|
+
/** The CALLER's bearer. Writes need one: the confirmation digest is keyed by it. */
|
|
174
|
+
token?: string;
|
|
175
|
+
/**
|
|
176
|
+
* The Lunora deployment URL the app talks to. A function is resolved on every
|
|
177
|
+
* call, so a server started before `lunora dev` picks the URL up once it exists.
|
|
178
|
+
* `undefined` means no deployment is running yet, and the call says so.
|
|
179
|
+
*/
|
|
180
|
+
url: string | (() => string | undefined);
|
|
181
|
+
version?: string;
|
|
182
|
+
/**
|
|
183
|
+
* The WebSocket class streams open with. Defaults to the global `WebSocket`, which a
|
|
184
|
+
* runtime without one (older Node) lacks, so such a host passes its own here.
|
|
185
|
+
*/
|
|
186
|
+
WebSocket?: typeof WebSocket;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Build an MCP `Server` with one tool per function in `openRpcSpec`. Transport
|
|
190
|
+
* agnostic: call `.connect(transport)` yourself.
|
|
191
|
+
*
|
|
192
|
+
* Throws at construction when the document is malformed or two functions share a
|
|
193
|
+
* tool name, so a bad integration fails at startup rather than on the first call.
|
|
194
|
+
*/
|
|
195
|
+
declare const createFunctionMcpServer: (options: FunctionMcpServerOptions) => Server;
|
|
196
|
+
export { AGENT_RUN_INPUT_SCHEMA as A, CallAgentToolOptions as C, FunctionMcpServerOptions as F, LunoraMcpServerOptions as L, McpAgentExposure as M, AGENT_STATUS_TOOL_NAME as a, agentToolDefinitions as b, callAgentTool as c, createFunctionMcpServer as d, createLunoraMcpServer as e, parseAgentsEnv as p };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { LunoraClient } from '@lunora/client';
|
|
2
2
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
3
|
-
import { b as ToolInputSchema, T as ToolDefinition, d as ToolResult } from "./compose.d-
|
|
3
|
+
import { b as ToolInputSchema, T as ToolDefinition, d as ToolResult } from "./compose.d-DiPnHeQv.mjs";
|
|
4
4
|
/**
|
|
5
5
|
* Agent exposure for the MCP server: a durable `@lunora/agent` run fronted as an
|
|
6
6
|
* MCP tool an external agent can call. The capability boundary is the MCP-server
|
|
@@ -149,4 +149,48 @@ interface LunoraMcpServerOptions {
|
|
|
149
149
|
* safe to run as a short-lived stdio process.
|
|
150
150
|
*/
|
|
151
151
|
declare const createLunoraMcpServer: (options: LunoraMcpServerOptions) => Server;
|
|
152
|
-
|
|
152
|
+
interface FunctionMcpServerOptions {
|
|
153
|
+
/**
|
|
154
|
+
* Advertise and allow mutation and action tools. Off by default. A closed write
|
|
155
|
+
* is not listed and is refused at dispatch.
|
|
156
|
+
*/
|
|
157
|
+
allowWrites?: boolean;
|
|
158
|
+
fetch?: typeof fetch;
|
|
159
|
+
/** The MCP server name clients show. Defaults to `lunora`. */
|
|
160
|
+
name?: string;
|
|
161
|
+
/**
|
|
162
|
+
* Told when a rewritten document cannot be read or built. The server keeps the tools it
|
|
163
|
+
* last built, so the error is reported here rather than failing the request.
|
|
164
|
+
*/
|
|
165
|
+
onReloadError?: (error: unknown) => void;
|
|
166
|
+
/**
|
|
167
|
+
* The `openRpcSpec` export of `_generated/openrpc`, or a function returning it. A
|
|
168
|
+
* function is called on every `tools/list` and `tools/call`, so the tools follow a
|
|
169
|
+
* document that codegen rewrites while the server runs. Return the same object
|
|
170
|
+
* while the document is unchanged: a different object rebuilds the tools.
|
|
171
|
+
*/
|
|
172
|
+
openRpcSpec: unknown;
|
|
173
|
+
/** The CALLER's bearer. Writes need one: the confirmation digest is keyed by it. */
|
|
174
|
+
token?: string;
|
|
175
|
+
/**
|
|
176
|
+
* The Lunora deployment URL the app talks to. A function is resolved on every
|
|
177
|
+
* call, so a server started before `lunora dev` picks the URL up once it exists.
|
|
178
|
+
* `undefined` means no deployment is running yet, and the call says so.
|
|
179
|
+
*/
|
|
180
|
+
url: string | (() => string | undefined);
|
|
181
|
+
version?: string;
|
|
182
|
+
/**
|
|
183
|
+
* The WebSocket class streams open with. Defaults to the global `WebSocket`, which a
|
|
184
|
+
* runtime without one (older Node) lacks, so such a host passes its own here.
|
|
185
|
+
*/
|
|
186
|
+
WebSocket?: typeof WebSocket;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Build an MCP `Server` with one tool per function in `openRpcSpec`. Transport
|
|
190
|
+
* agnostic: call `.connect(transport)` yourself.
|
|
191
|
+
*
|
|
192
|
+
* Throws at construction when the document is malformed or two functions share a
|
|
193
|
+
* tool name, so a bad integration fails at startup rather than on the first call.
|
|
194
|
+
*/
|
|
195
|
+
declare const createFunctionMcpServer: (options: FunctionMcpServerOptions) => Server;
|
|
196
|
+
export { AGENT_RUN_INPUT_SCHEMA as A, CallAgentToolOptions as C, FunctionMcpServerOptions as F, LunoraMcpServerOptions as L, McpAgentExposure as M, AGENT_STATUS_TOOL_NAME as a, agentToolDefinitions as b, callAgentTool as c, createFunctionMcpServer as d, createLunoraMcpServer as e, parseAgentsEnv as p };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a="1.0.0-alpha.258";const o={version:a};export{o as p};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as E,isInternalCode as d,getCatalogEntry as c}from"@lunora/errors";const l=e=>{let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)},p=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n+=1)r[n]=t.codePointAt(n)??0;return r},s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",O=e=>{let t="",r=0;const n=e.length-2;for(;r<n;r+=3){const o=e[r]<<16|e[r+1]<<8|e[r+2];t+=s.charAt(o>>18&63)+s.charAt(o>>12&63)+s.charAt(o>>6&63)+s.charAt(o&63)}const f=e.length-r;if(f===1){const o=e[r]<<16;t+=s.charAt(o>>18&63)+s.charAt(o>>12&63)}else if(f===2){const o=e[r]<<16|e[r+1]<<8;t+=s.charAt(o>>18&63)+s.charAt(o>>12&63)+s.charAt(o>>6&63)}return t},_=e=>{const t=e.replaceAll("-","+").replaceAll("_","/"),r=t+"=".repeat((4-t.length%4)%4);return p(r)},u=(e,t)=>{if(typeof t=="bigint")return t.toString();if(t instanceof Map)return[...t.keys()].every(r=>typeof r=="string")?Object.fromEntries(t):[...t];if(t instanceof Set)return[...t];if(t instanceof ArrayBuffer)return l(new Uint8Array(t));if(ArrayBuffer.isView(t)){const r=t;return l(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}return t},A=e=>JSON.parse(JSON.stringify(e,u)),R=e=>({content:[{text:e===void 0?"null":JSON.stringify(e,u,2),type:"text"}]}),x=e=>({...R(e),structuredContent:A(e)}),i=(e,t)=>({content:[{text:`${e}: ${t}`,type:"text"}],isError:!0,structuredContent:{code:e,message:t}}),a="the tool call failed unexpectedly",g=Symbol.for("lunora.serverVerdict"),w=e=>{if(e instanceof E){const{code:t}=e;return i(t,d(t)?c(t)?.title??a:e.message)}if(e instanceof Error){const{code:t}=e;if(typeof t=="string"&&c(t)!==void 0&&e[g]===!0)return i(t,d(t)?c(t)?.title??a:e.message)}return i("INTERNAL",a)},y={description:"Set on an error result: the machine-readable error code.",type:"string"},S={description:"Set on an error result: a message that is safe to show.",type:"string"},h={properties:{code:y,message:S},required:["code","message"],type:"object"},C=e=>{if(e.anyOf?.includes(h)===!0)return e;const{$defs:t,definitions:r,...n}=e;return{...t===void 0?{}:{$defs:t},...r===void 0?{}:{definitions:r},anyOf:[n,h],type:"object"}};export{w as a,R as b,_ as c,i as e,p as f,u as j,x as o,O as t,C as w};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{getCatalogEntry as q,resolveHint as Q,findIssueSolution as Y,isInternalCode as I,LunoraError as s}from"@lunora/errors";import{w as G,e as u,o as J,b as l,t as V,c as X,a as z}from"./tool-result-CPDsNNuJ.mjs";import{OBSERVABILITY_TOOL_NAMES as Z,OBSERVABILITY_TOOL_DEFINITIONS as ee,callObservabilityTool as te}from"./OBSERVABILITY_TOOL_DEFINITIONS-DQ7AUah0.mjs";import{ADMIN_FUNCTIONS as ne}from"@lunora/shard-engine";import{stableStringify as oe}from"@lunora/wire";import{m as ie}from"./promise-memo-OqVPWoUX.mjs";const re={destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},E="https://lunora.sh/docs/errors",se={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"},ae={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"},D=[{annotations:{...re,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:se,name:"lunora_explain_error",outputSchema:G(ae)}],ce=new Set(D.map(e=>e.name)),A=e=>typeof e=="string"&&e.length>0?e:void 0,de=e=>typeof e=="string"?e:e.join(`
|
|
2
|
+
`),le=(e,t)=>t?.docsUrl!==void 0?t.docsUrl:e===void 0||t===void 0||I(e)?E:`${E}#${e.toLowerCase()}`,ue=(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:le(e,n),found:n!==void 0||i!==void 0};return e!==void 0&&(r.code=e,I(e)&&(r.internal=!0)),n!==void 0&&(r.status=n.status,r.title=n.title),o!==void 0&&(r.hint=de(o)),i!==void 0&&(r.solution={body:i.body,header:i.header,id:i.id}),r},he=(e,t)=>{if(e!=="lunora_explain_error")return u("NOT_FOUND",`unknown error tool: ${e}`);const n=A(t.code),o=A(t.message);return n===void 0&&o===void 0?u("BAD_REQUEST",'lunora_explain_error needs a "code" or a "message" (or both); received neither.'):J(ue(n,o))},pe={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},fe={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"},C=[{annotations:{...pe,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:fe,name:"lunora_find_related"}],me=new Set(C.map(e=>e.name)),ge=e=>{const{cursor:t,depth:n,direction:o,edges:i,limit:r}=e;if(t!=null&&typeof t!="string")throw new s("BAD_REQUEST","findRelated: `cursor` must be a string");if(n!==void 0&&typeof n!="number")throw new s("BAD_REQUEST","findRelated: `depth` must be a number");if(o!==void 0&&o!=="both"&&o!=="in"&&o!=="out")throw new s("BAD_REQUEST",'findRelated: `direction` must be one of "in", "out" or "both"');if(r!==void 0&&typeof r!="number")throw new s("BAD_REQUEST","findRelated: `limit` must be a number");if(i!==void 0&&(!Array.isArray(i)||!i.every(a=>typeof a=="string")))throw new s("BAD_REQUEST","findRelated: `edges` must be an array of edge-name strings")},ye=e=>{const{cursor:t,depth:n,direction:o,edges:i,id:r,limit:a,shardKey:d,table:c}=e;if(typeof c!="string"||c.trim()==="")throw new s("BAD_REQUEST","findRelated: `table` is required");if(typeof r!="string"||r.trim()==="")throw new s("BAD_REQUEST","findRelated: `id` is required");if(ge(e),d!==void 0&&(typeof d!="string"||d.trim()===""))throw new s("BAD_REQUEST","findRelated: `shardKey` must be a non-empty string when given");return{args:{id:r,table:c,...typeof t=="string"?{cursor:t}:{},...n===void 0?{}:{depth:n},...o===void 0?{}:{direction:o},...i===void 0?{}:{edges:i},...a===void 0?{}:{limit:a}},shardKey:d}},we=async(e,t,n)=>{if(t!=="lunora_find_related")throw new s("INTERNAL",`unknown row-read tool: ${t}`);const{args:o,shardKey:i}=ye(n),r={__lunoraRef:ne.findRelated};return l(await e.query(r,o,{...i===void 0?{}:{shardKey:i}}))},g=new TextEncoder,_e=Array.from({length:32},(e,t)=>t);new RegExp(`[${_e.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Ee=64,Ae=new Map,L=async e=>ie(Ae,e,async()=>crypto.subtle.importKey("raw",g.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),Ee),Oe=async(e,t)=>{const n=await L(e),o=await crypto.subtle.sign("HMAC",n,g.encode(t));return V(new Uint8Array(o))},Te=async(e,t,n)=>{const o=await L(e);return crypto.subtle.verify("HMAC",o,n,g.encode(t))},be="lunora-mcp-write-confirmation-v1",U=600*1e3,k=".",H=e=>{const t=e.getAuthToken();if(t===null||t==="")throw new s("UNAUTHORIZED","write confirmation needs a bearer token for this deployment: 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}`},P=(e,t)=>`${oe(e)}\0${String(t)}`,Re=async(e,t)=>{const n=Date.now()+U,o=await Oe(H(e),P(t,n));return{actionDigest:`${String(n)}${k}${o}`,expiresAt:n}},ve=async(e,t,n)=>{const o=n.indexOf(k);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=X(n.slice(o+1))}catch{return"mismatch"}return await Te(H(e),P(t,i),r)?"valid":"mismatch"},Ne="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:Ne,type:"string"}},Ie=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}},M="«sensitive»",De=(e,t)=>{if(t.length===0)return e;const n=Object.fromEntries(Object.entries(e.args).map(([o,i])=>[o,t.includes(o)?M:i]));return{...e,args:n}},Ce=["functionPath","args","shardKey","idempotencyKey"],Le=e=>e.length>1?`${e.slice(0,-1).join(", ")} and ${e.at(-1)??""}`:e.join(""),Ue=(e,t,n,o)=>l({actionDigest:t.actionDigest,expiresAt:new Date(t.expiresAt).toISOString(),nextStep:`Show proposedAction to a human. To execute, call ${e.tool} again with the IDENTICAL ${Le(o)}, plus confirmed: true and this actionDigest, before expiresAt. Resend the REAL values of any argument shown as "${M}": that placeholder is display only and will not verify. Nothing has been written or called yet.`,proposedAction:De(e,n),status:"action_required"}),ke=async(e,t,n,o=[],i=Ce)=>{if(!n.confirmed||n.actionDigest===void 0)return Ue(t,await Re(e,t),o,i);const r=await ve(e,t,n.actionDigest);if(r!=="valid")return r==="expired"?u("CONFIRMATION_EXPIRED",`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.`):u("CONFIRMATION_MISMATCH",`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.`)},x={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"},He={properties:{functionPath:{description:'Function reference, e.g. "messages:send"',type:"string"}},required:["functionPath"],type:"object"},p={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},$=[{annotations:{...p,title:"List deployment functions"},description:"List the deployment's public functions (queries, mutations, actions) with their kinds.",inputSchema:O,name:"lunora_list_functions"},{annotations:{...p,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:{...p,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:He,name:"lunora_get_function_schema"},{annotations:{...p,title:"Run a query"},description:"Run a query and return its result. Read-only.",inputSchema:x,name:"lunora_run_query"}],Pe=new Set($.map(e=>e.name)),T={properties:{...x.properties,...Se},required:["functionPath"],type:"object"},b='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. ${b}`,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. ${b}`,inputSchema:T,name:"lunora_run_action"}],Me=new Set(F.map(e=>e.name)),B=e=>{const{functionPath:t}=e;if(typeof t!="string"||t.length===0)throw new s("BAD_REQUEST",'"functionPath" is required and must be a non-empty string');return t},R=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),v=e=>Array.isArray(e)?"an array":`a ${typeof e}`,xe=e=>{if(e==null)return{};if(typeof e=="string"){let t;try{t=JSON.parse(e)}catch{throw new s("BAD_REQUEST",'"args" must be a JSON object; received a string that is not valid JSON')}if(!R(t))throw new s("BAD_REQUEST",`"args" must be a JSON object; the provided string decoded to ${v(t)}`);return t}if(!R(e))throw new s("BAD_REQUEST",`"args" must be a JSON object, got ${v(e)}`);return e},K=e=>{const t=B(e),n=xe(e.args),o=typeof e.shardKey=="string"&&e.shardKey.length>0?e.shardKey:void 0;return{args:n,functionPath:t,shardKey:o}},W=e=>({__lunoraRef:e}),$e=3e4,h=new WeakMap,m=e=>{const t=Date.now(),n=h.get(e);if(n!==void 0&&n.expiresAt>t)return n.promise;const o=e.listFunctions().catch(i=>{throw h.get(e)?.promise===o&&h.delete(e),i});return h.set(e,{expiresAt:t+$e,promise:o}),o},j=async(e,t,n)=>{const i=(await m(e)).find(r=>r.path===t);if(i===void 0)throw new s("NOT_FOUND",`function not found or not public: ${t}`);if(i.kind!==n)throw new s("BAD_REQUEST",`function ${t} is a ${i.kind}, not a ${n}`);return i},Fe=async(e,t,n,o,i,r)=>{const a=Ie(i);return ke(e,{...o,idempotencyKey:a.idempotencyKey,kind:n,tool:t},a,r)},Be=e=>(e.args??[]).filter(t=>t.sensitive===!0).map(t=>t.name),Ke=async(e,t,n)=>{switch(t){case"lunora_get_function_schema":{const o=B(n),r=(await m(e)).find(a=>a.path===o);return r===void 0?u("NOT_FOUND",`function not found: ${o}`):l({args:r.args??[],kind:r.kind,path:r.path})}case"lunora_list_functions":return l(await m(e));case"lunora_list_tables":return l(await e.listGlobalTables());case"lunora_run_query":{const{args:o,functionPath:i,shardKey:r}=K(n);return await j(e,i,"query"),l(await e.query(W(i),o,{shardKey:r}))}default:throw new s("INTERNAL",`unknown read-only tool: ${t}`)}},We=async(e,t,n)=>{if(t!=="lunora_run_action"&&t!=="lunora_run_mutation")throw new s("INTERNAL",`unknown write tool: ${t}`);const o=t==="lunora_run_action"?"action":"mutation",{args:i,functionPath:r,shardKey:a}=K(n);h.delete(e);const d=await j(e,r,o),c=Be(d),w=await Fe(e,t,o,{args:i,functionPath:r,shardKey:a},n,c);if(w!==void 0)return w;const _=c.length===0?W(r):{__lunoraRef:r,sensitive:!0};return l(o==="action"?await e.action(_,i,{shardKey:a}):await e.mutation(_,i,{onlineOnly:!0,shardKey:a}))},N="lunora:data-read",S="lunora:observability",je=e=>e===!0,f=[{call:Ke,definitions:$,names:Pe},{call:(e,t,n)=>he(t,n),definitions:D,names:ce},{call:we,definitions:C,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 ${N} scope.`,scope:N},names:me},{call:te,definitions:ee,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 ${S} scope.`,scope:S},names:Z},{call:We,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:Me}],y=(e,t)=>e.gate!==void 0&&!je(t[e.gate.flag])?e.gate:void 0,Xe=(e,t=!1,n=!1)=>{const o={allowDataReads:n,allowObservability:t,allowWrites:e};return f.filter(i=>y(i,o)===void 0).flatMap(i=>i.definitions)},ze=async(e,t,n,o=!1,i=!1,r=!1)=>{const a=f.find(c=>c.names.has(t));if(a===void 0)return u("NOT_FOUND",`unknown tool: ${t}`);const d=y(a,{allowDataReads:r,allowObservability:i,allowWrites:o});if(d!==void 0)return u("FORBIDDEN",d.refuse(t));try{return await a.call(e,t,n)}catch(c){return z(c)}},Ze=(e,t)=>{const n=f.find(o=>o.names.has(e));if(!(n?.gate?.scope===void 0||y(n,t)!==void 0))return n.gate.scope},et=f.flatMap(e=>e.gate?.scope===void 0?[]:[{flag:e.gate.flag,scope:e.gate.scope}]);export{N as D,D as E,S as O,$ as R,et as S,F as W,he as a,ce as b,ze as c,Me as d,Se as e,Ie as f,ke as g,C as h,xe as r,Ze as s,Xe as t};
|
package/dist/worker/index.d.mts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { L as LunoraMcpServerOptions } from "../packem_shared/server.d-
|
|
1
|
+
import { L as LunoraMcpServerOptions } from "../packem_shared/function-server.d-D_0-WiS2.mjs";
|
|
2
2
|
export { A as AGENT_RUN_INPUT_SCHEMA, a as AGENT_STATUS_TOOL_NAME,
|
|
3
3
|
/** Worker-safe entry: fetch handlers and tool composition, with no stdio transport or `node:*` imports. */
|
|
4
|
-
type C as CallAgentToolOptions,
|
|
4
|
+
type C as CallAgentToolOptions, type F as FunctionMcpServerOptions,
|
|
5
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-
|
|
6
|
+
type M as McpAgentExposure, b as agentToolDefinitions, c as callAgentTool, d as createFunctionMcpServer, p as parseAgentsEnv } from "../packem_shared/function-server.d-D_0-WiS2.mjs";
|
|
7
7
|
import { M as McpFetchHandler } from "../packem_shared/serve-stateless.d-DD5arqFx.mjs";
|
|
8
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, d as ToolResult, h as ToolAnnotations, b as ToolInputSchema } from "../packem_shared/compose.d-
|
|
10
|
-
export { type M as McpServerInfo, type a as McpTool, e as createToolServer } from "../packem_shared/compose.d-
|
|
9
|
+
import { T as ToolDefinition, d as ToolResult, h as ToolAnnotations, b as ToolInputSchema } from "../packem_shared/compose.d-DiPnHeQv.mjs";
|
|
10
|
+
export { type M as McpServerInfo, type a as McpTool, e as createToolServer } from "../packem_shared/compose.d-DiPnHeQv.mjs";
|
|
11
11
|
import { LunoraClient } from '@lunora/client';
|
|
12
12
|
import '@modelcontextprotocol/sdk/server/index.js';
|
|
13
13
|
import '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
|
package/dist/worker/index.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { L as LunoraMcpServerOptions } from "../packem_shared/server.d-
|
|
1
|
+
import { L as LunoraMcpServerOptions } from "../packem_shared/function-server.d-ByIkBRXs.js";
|
|
2
2
|
export { A as AGENT_RUN_INPUT_SCHEMA, a as AGENT_STATUS_TOOL_NAME,
|
|
3
3
|
/** Worker-safe entry: fetch handlers and tool composition, with no stdio transport or `node:*` imports. */
|
|
4
|
-
type C as CallAgentToolOptions,
|
|
4
|
+
type C as CallAgentToolOptions, type F as FunctionMcpServerOptions,
|
|
5
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-
|
|
6
|
+
type M as McpAgentExposure, b as agentToolDefinitions, c as callAgentTool, d as createFunctionMcpServer, p as parseAgentsEnv } from "../packem_shared/function-server.d-ByIkBRXs.js";
|
|
7
7
|
import { M as McpFetchHandler } from "../packem_shared/serve-stateless.d-DD5arqFx.js";
|
|
8
8
|
export { D as DEFAULT_MAX_REQUEST_BYTES, type S as ServeStatelessOptions, s as serveStateless } from "../packem_shared/serve-stateless.d-DD5arqFx.js";
|
|
9
|
-
import { T as ToolDefinition, d as ToolResult, h as ToolAnnotations, b as ToolInputSchema } from "../packem_shared/compose.d-
|
|
10
|
-
export { type M as McpServerInfo, type a as McpTool, e as createToolServer } from "../packem_shared/compose.d-
|
|
9
|
+
import { T as ToolDefinition, d as ToolResult, h as ToolAnnotations, b as ToolInputSchema } from "../packem_shared/compose.d-DiPnHeQv.js";
|
|
10
|
+
export { type M as McpServerInfo, type a as McpTool, e as createToolServer } from "../packem_shared/compose.d-DiPnHeQv.js";
|
|
11
11
|
import { LunoraClient } from '@lunora/client';
|
|
12
12
|
import '@modelcontextprotocol/sdk/server/index.js';
|
|
13
13
|
import '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
|
package/dist/worker/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AGENT_RUN_INPUT_SCHEMA as r,AGENT_STATUS_TOOL_NAME as t,agentToolDefinitions as T,callAgentTool as a,parseAgentsEnv as
|
|
1
|
+
import{AGENT_RUN_INPUT_SCHEMA as r,AGENT_STATUS_TOOL_NAME as t,agentToolDefinitions as T,callAgentTool as a,parseAgentsEnv as c}from"../packem_shared/AGENT_RUN_INPUT_SCHEMA-BGbKIek4.mjs";import{createAuthedMcpFetchHandler as _,mcpTokenScopes as E}from"../packem_shared/createAuthedMcpFetchHandler-CuW8wLOn.mjs";import{createToolServer as n}from"../packem_shared/createToolServer-CHAjfuNx.mjs";import{createFunctionMcpServer as O}from"../packem_shared/createFunctionMcpServer-cU_kZVAn.mjs";import{createMcpFetchHandler as s}from"../packem_shared/createMcpFetchHandler-CcYLsaGa.mjs";import{createPaidMcpServer as N}from"../packem_shared/createPaidMcpServer-CdDLw3G4.mjs";import{R as m,W as x,c as i,t as D}from"../packem_shared/tools-Bylr9LPQ.mjs";import{DEFAULT_MAX_REQUEST_BYTES as L,serveStateless as M}from"../packem_shared/DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs";import{OBSERVABILITY_TOOL_DEFINITIONS as v}from"../packem_shared/OBSERVABILITY_TOOL_DEFINITIONS-DQ7AUah0.mjs";export{r as AGENT_RUN_INPUT_SCHEMA,t as AGENT_STATUS_TOOL_NAME,L as DEFAULT_MAX_REQUEST_BYTES,v as OBSERVABILITY_TOOL_DEFINITIONS,m as READ_ONLY_TOOL_DEFINITIONS,x as WRITE_TOOL_DEFINITIONS,T as agentToolDefinitions,a as callAgentTool,i as callTool,_ as createAuthedMcpFetchHandler,O as createFunctionMcpServer,s as createMcpFetchHandler,N as createPaidMcpServer,n as createToolServer,E as mcpTokenScopes,c as parseAgentsEnv,M as serveStateless,D as toolDefinitions};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/mcp",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.259",
|
|
4
4
|
"description": "Model Context Protocol server exposing a Lunora deployment to AI agents",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai-agents",
|
|
@@ -62,9 +62,9 @@
|
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
64
64
|
"@cfworker/json-schema": "^4.1.1",
|
|
65
|
-
"@lunora/client": "1.0.0-alpha.
|
|
65
|
+
"@lunora/client": "1.0.0-alpha.246",
|
|
66
66
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
67
|
-
"@lunora/shard-engine": "1.0.0-alpha.
|
|
67
|
+
"@lunora/shard-engine": "1.0.0-alpha.156",
|
|
68
68
|
"@lunora/wire": "1.0.0-alpha.2",
|
|
69
69
|
"@modelcontextprotocol/sdk": "^1.32.0"
|
|
70
70
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{D as E,O as _,R as o,e as s,S,W as a,d as D,c as N,s as A,t as R}from"./tools-BrvavFhl.mjs";import{OBSERVABILITY_TOOL_DEFINITIONS as r}from"./OBSERVABILITY_TOOL_DEFINITIONS-DrY5Gp38.mjs";import"./tool-result--Yq36pE-.mjs";export{E as DATA_READ_SCOPE,_ as OBSERVABILITY_SCOPE,r as OBSERVABILITY_TOOL_DEFINITIONS,o as READ_ONLY_TOOL_DEFINITIONS,s as ROW_READ_TOOL_DEFINITIONS,S as SCOPED_GATES,a as WRITE_TOOL_DEFINITIONS,D as WRITE_TOOL_NAMES,N as callTool,A as scopeForTool,R as toolDefinitions};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraClient as f}from"@lunora/client";import{LunoraError as m}from"@lunora/errors";import{Server as w}from"@modelcontextprotocol/sdk/server/index.js";import{ListToolsRequestSchema as d,CallToolRequestSchema as h}from"@modelcontextprotocol/sdk/types.js";import{agentToolDefinitions as A,isAgentToolName as M,callAgentTool as T}from"./AGENT_RUN_INPUT_SCHEMA-BBVvXopY.mjs";import{t as R,c as k}from"./tools-BrvavFhl.mjs";var N="1.0.0-alpha.257";const E={version:N},L="lunora",y=e=>{if(e.client!==void 0)return e.client;if(e.url===void 0)throw new m("INTERNAL","createLunoraMcpServer requires either a `client` or a `url`");if(e.token===void 0||e.token.length===0)throw new m("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 f({fetch:e.fetch,url:e.url});return r.setAuthToken(e.token),r},C=e=>{const r=y(e),n=e.allowWrites??!1,s=e.allowAgents??!1,t=e.agents??[],o=typeof e.token=="string"&&e.token.length>0,i=e.allowObservability===!0&&o,c=e.allowDataReads===!0&&o,a=new w({name:L,version:e.version??E.version},{capabilities:{tools:{}}});return a.setRequestHandler(d,()=>({tools:[...R(n,i,c),...A(t,s)]})),a.setRequestHandler(h,async v=>{const{arguments:g,name:l}=v.params,u=g??{};return M(l,t)?await T(r,l,u,{allowAgents:s,exposures:t,...e.agentMaxWaitMs===void 0?{}:{maxWaitMs:e.agentMaxWaitMs},...e.agentPollIntervalMs===void 0?{}:{pollIntervalMs:e.agentPollIntervalMs}}):await k(r,l,u,n,i,c)}),a};export{C as createLunoraMcpServer,y as resolveClient};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as E,isInternalCode as l,getCatalogEntry as c}from"@lunora/errors";const u=t=>{let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e)},A=t=>{const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.codePointAt(n)??0;return r},s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",O=t=>{let e="",r=0;const n=t.length-2;for(;r<n;r+=3){const o=t[r]<<16|t[r+1]<<8|t[r+2];e+=s.charAt(o>>18&63)+s.charAt(o>>12&63)+s.charAt(o>>6&63)+s.charAt(o&63)}const f=t.length-r;if(f===1){const o=t[r]<<16;e+=s.charAt(o>>18&63)+s.charAt(o>>12&63)}else if(f===2){const o=t[r]<<16|t[r+1]<<8;e+=s.charAt(o>>18&63)+s.charAt(o>>12&63)+s.charAt(o>>6&63)}return e},_=t=>{const e=t.replaceAll("-","+").replaceAll("_","/"),r=e+"=".repeat((4-e.length%4)%4);return A(r)},h=(t,e)=>{if(typeof e=="bigint")return e.toString();if(e instanceof ArrayBuffer)return u(new Uint8Array(e));if(ArrayBuffer.isView(e)){const r=e;return u(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}return e},R=t=>JSON.parse(JSON.stringify(t,h)),g=t=>({content:[{text:t===void 0?"null":JSON.stringify(t,h,2),type:"text"}]}),x=t=>({...g(t),structuredContent:R(t)}),i=(t,e)=>({content:[{text:`${t}: ${e}`,type:"text"}],isError:!0,structuredContent:{code:t,message:e}}),a="the tool call failed unexpectedly",p=Symbol.for("lunora.serverVerdict"),w=t=>{if(t instanceof E){const{code:e}=t;return i(e,l(e)?c(e)?.title??a:t.message)}if(t instanceof Error){const{code:e}=t;if(typeof e=="string"&&c(e)!==void 0&&t[p]===!0)return i(e,l(e)?c(e)?.title??a:t.message)}return i("INTERNAL",a)},y={description:"Set on an error result: the machine-readable error code.",type:"string"},S={description:"Set on an error result: a message that is safe to show.",type:"string"},d={properties:{code:y,message:S},required:["code","message"],type:"object"},C=t=>{if(t.anyOf?.includes(d)===!0)return t;const{$defs:e,definitions:r,...n}=t;return{...e===void 0?{}:{$defs:e},...r===void 0?{}:{definitions:r},anyOf:[n,d],type:"object"}};export{w as a,g as b,i as e,_ as f,x as o,O as t,C as w};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{getCatalogEntry as j,resolveHint as Q,findIssueSolution as Y,isInternalCode as I,LunoraError as s}from"@lunora/errors";import{w as G,e as u,o as J,b as l,t as V,f as X,a as z}from"./tool-result--Yq36pE-.mjs";import{OBSERVABILITY_TOOL_NAMES as Z,OBSERVABILITY_TOOL_DEFINITIONS as ee,callObservabilityTool as te}from"./OBSERVABILITY_TOOL_DEFINITIONS-DrY5Gp38.mjs";import{ADMIN_FUNCTIONS as ne}from"@lunora/shard-engine";import{stableStringify as oe}from"@lunora/wire";import{m as ie}from"./promise-memo-OqVPWoUX.mjs";const re={destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},E="https://lunora.sh/docs/errors",se={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"},ae={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"},D=[{annotations:{...re,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:se,name:"lunora_explain_error",outputSchema:G(ae)}],ce=new Set(D.map(e=>e.name)),A=e=>typeof e=="string"&&e.length>0?e:void 0,de=e=>typeof e=="string"?e:e.join(`
|
|
2
|
-
`),le=(e,t)=>t?.docsUrl!==void 0?t.docsUrl:e===void 0||t===void 0||I(e)?E:`${E}#${e.toLowerCase()}`,ue=(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:Y(t),r={docsUrl:le(e,n),found:n!==void 0||i!==void 0};return e!==void 0&&(r.code=e,I(e)&&(r.internal=!0)),n!==void 0&&(r.status=n.status,r.title=n.title),o!==void 0&&(r.hint=de(o)),i!==void 0&&(r.solution={body:i.body,header:i.header,id:i.id}),r},he=(e,t)=>{if(e!=="lunora_explain_error")return u("NOT_FOUND",`unknown error tool: ${e}`);const n=A(t.code),o=A(t.message);return n===void 0&&o===void 0?u("BAD_REQUEST",'lunora_explain_error needs a "code" or a "message" (or both); received neither.'):J(ue(n,o))},pe={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},fe={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"},C=[{annotations:{...pe,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:fe,name:"lunora_find_related"}],me=new Set(C.map(e=>e.name)),ge=e=>{const{cursor:t,depth:n,direction:o,edges:i,limit:r}=e;if(t!=null&&typeof t!="string")throw new s("BAD_REQUEST","findRelated: `cursor` must be a string");if(n!==void 0&&typeof n!="number")throw new s("BAD_REQUEST","findRelated: `depth` must be a number");if(o!==void 0&&o!=="both"&&o!=="in"&&o!=="out")throw new s("BAD_REQUEST",'findRelated: `direction` must be one of "in", "out" or "both"');if(r!==void 0&&typeof r!="number")throw new s("BAD_REQUEST","findRelated: `limit` must be a number");if(i!==void 0&&(!Array.isArray(i)||!i.every(a=>typeof a=="string")))throw new s("BAD_REQUEST","findRelated: `edges` must be an array of edge-name strings")},ye=e=>{const{cursor:t,depth:n,direction:o,edges:i,id:r,limit:a,shardKey:d,table:c}=e;if(typeof c!="string"||c.trim()==="")throw new s("BAD_REQUEST","findRelated: `table` is required");if(typeof r!="string"||r.trim()==="")throw new s("BAD_REQUEST","findRelated: `id` is required");if(ge(e),d!==void 0&&(typeof d!="string"||d.trim()===""))throw new s("BAD_REQUEST","findRelated: `shardKey` must be a non-empty string when given");return{args:{id:r,table:c,...typeof t=="string"?{cursor:t}:{},...n===void 0?{}:{depth:n},...o===void 0?{}:{direction:o},...i===void 0?{}:{edges:i},...a===void 0?{}:{limit:a}},shardKey:d}},we=async(e,t,n)=>{if(t!=="lunora_find_related")throw new s("INTERNAL",`unknown row-read tool: ${t}`);const{args:o,shardKey:i}=ye(n),r={__lunoraRef:ne.findRelated};return l(await e.query(r,o,{...i===void 0?{}:{shardKey:i}}))},g=new TextEncoder,_e=Array.from({length:32},(e,t)=>t);new RegExp(`[${_e.map(e=>String.fromCodePoint(e)).join("")}]`,"u");const Ee=64,Ae=new Map,L=async e=>ie(Ae,e,async()=>crypto.subtle.importKey("raw",g.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),Ee),Oe=async(e,t)=>{const n=await L(e),o=await crypto.subtle.sign("HMAC",n,g.encode(t));return V(new Uint8Array(o))},Te=async(e,t,n)=>{const o=await L(e);return crypto.subtle.verify("HMAC",o,n,g.encode(t))},be="lunora-mcp-write-confirmation-v1",U=600*1e3,k=".",H=e=>{const t=e.getAuthToken();if(t===null||t==="")throw new s("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}`},P=(e,t)=>`${oe(e)}\0${String(t)}`,Re=async(e,t)=>{const n=Date.now()+U,o=await Oe(H(e),P(t,n));return{actionDigest:`${String(n)}${k}${o}`,expiresAt:n}},ve=async(e,t,n)=>{const o=n.indexOf(k);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=X(n.slice(o+1))}catch{return"mismatch"}return await Te(H(e),P(t,i),r)?"valid":"mismatch"},Ne="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:Ne,type:"string"}},Ie=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}},M="«sensitive»",De=(e,t)=>{if(t.length===0)return e;const n=Object.fromEntries(Object.entries(e.args).map(([o,i])=>[o,t.includes(o)?M:i]));return{...e,args:n}},Ce=(e,t,n)=>l({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. Resend the REAL values of any argument shown as "${M}": that placeholder is display only and will not verify. Nothing has been written or called yet.`,proposedAction:De(e,n),status:"action_required"}),Le=async(e,t,n,o=[])=>{if(!n.confirmed||n.actionDigest===void 0)return Ce(t,await Re(e,t),o);const i=await ve(e,t,n.actionDigest);if(i!=="valid")return i==="expired"?u("CONFIRMATION_EXPIRED",`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.`):u("CONFIRMATION_MISMATCH",`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.`)},x={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"},Ue={properties:{functionPath:{description:'Function reference, e.g. "messages:send"',type:"string"}},required:["functionPath"],type:"object"},p={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},$=[{annotations:{...p,title:"List deployment functions"},description:"List the deployment's public functions (queries, mutations, actions) with their kinds.",inputSchema:O,name:"lunora_list_functions"},{annotations:{...p,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:{...p,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:Ue,name:"lunora_get_function_schema"},{annotations:{...p,title:"Run a query"},description:"Run a query and return its result. Read-only.",inputSchema:x,name:"lunora_run_query"}],ke=new Set($.map(e=>e.name)),T={properties:{...x.properties,...Se},required:["functionPath"],type:"object"},b='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. ${b}`,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. ${b}`,inputSchema:T,name:"lunora_run_action"}],He=new Set(F.map(e=>e.name)),B=e=>{const{functionPath:t}=e;if(typeof t!="string"||t.length===0)throw new s("BAD_REQUEST",'"functionPath" is required and must be a non-empty string');return t},R=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),v=e=>Array.isArray(e)?"an array":`a ${typeof e}`,Pe=e=>{if(e==null)return{};if(typeof e=="string"){let t;try{t=JSON.parse(e)}catch{throw new s("BAD_REQUEST",'"args" must be a JSON object; received a string that is not valid JSON')}if(!R(t))throw new s("BAD_REQUEST",`"args" must be a JSON object; the provided string decoded to ${v(t)}`);return t}if(!R(e))throw new s("BAD_REQUEST",`"args" must be a JSON object, got ${v(e)}`);return e},K=e=>{const t=B(e),n=Pe(e.args),o=typeof e.shardKey=="string"&&e.shardKey.length>0?e.shardKey:void 0;return{args:n,functionPath:t,shardKey:o}},W=e=>({__lunoraRef:e}),Me=3e4,h=new WeakMap,m=e=>{const t=Date.now(),n=h.get(e);if(n!==void 0&&n.expiresAt>t)return n.promise;const o=e.listFunctions().catch(i=>{throw h.get(e)?.promise===o&&h.delete(e),i});return h.set(e,{expiresAt:t+Me,promise:o}),o},q=async(e,t,n)=>{const i=(await m(e)).find(r=>r.path===t);if(i===void 0)throw new s("NOT_FOUND",`function not found or not public: ${t}`);if(i.kind!==n)throw new s("BAD_REQUEST",`function ${t} is a ${i.kind}, not a ${n}`);return i},xe=async(e,t,n,o,i,r)=>{const a=Ie(i);return Le(e,{...o,idempotencyKey:a.idempotencyKey,kind:n,tool:t},a,r)},$e=e=>(e.args??[]).filter(t=>t.sensitive===!0).map(t=>t.name),Fe=async(e,t,n)=>{switch(t){case"lunora_get_function_schema":{const o=B(n),r=(await m(e)).find(a=>a.path===o);return r===void 0?u("NOT_FOUND",`function not found: ${o}`):l({args:r.args??[],kind:r.kind,path:r.path})}case"lunora_list_functions":return l(await m(e));case"lunora_list_tables":return l(await e.listGlobalTables());case"lunora_run_query":{const{args:o,functionPath:i,shardKey:r}=K(n);return await q(e,i,"query"),l(await e.query(W(i),o,{shardKey:r}))}default:throw new s("INTERNAL",`unknown read-only tool: ${t}`)}},Be=async(e,t,n)=>{if(t!=="lunora_run_action"&&t!=="lunora_run_mutation")throw new s("INTERNAL",`unknown write tool: ${t}`);const o=t==="lunora_run_action"?"action":"mutation",{args:i,functionPath:r,shardKey:a}=K(n);h.delete(e);const d=await q(e,r,o),c=$e(d),w=await xe(e,t,o,{args:i,functionPath:r,shardKey:a},n,c);if(w!==void 0)return w;const _=c.length===0?W(r):{__lunoraRef:r,sensitive:!0};return l(o==="action"?await e.action(_,i,{shardKey:a}):await e.mutation(_,i,{onlineOnly:!0,shardKey:a}))},N="lunora:data-read",S="lunora:observability",Ke=e=>e===!0,f=[{call:Fe,definitions:$,names:ke},{call:(e,t,n)=>he(t,n),definitions:D,names:ce},{call:we,definitions:C,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 ${N} scope.`,scope:N},names:me},{call:te,definitions:ee,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 ${S} scope.`,scope:S},names:Z},{call:Be,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:He}],y=(e,t)=>e.gate!==void 0&&!Ke(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=>y(i,o)===void 0).flatMap(i=>i.definitions)},Ve=async(e,t,n,o=!1,i=!1,r=!1)=>{const a=f.find(c=>c.names.has(t));if(a===void 0)return u("NOT_FOUND",`unknown tool: ${t}`);const d=y(a,{allowDataReads:r,allowObservability:i,allowWrites:o});if(d!==void 0)return u("FORBIDDEN",d.refuse(t));try{return await a.call(e,t,n)}catch(c){return z(c)}},Xe=(e,t)=>{const n=f.find(o=>o.names.has(e));if(!(n?.gate?.scope===void 0||y(n,t)!==void 0))return n.gate.scope},ze=f.flatMap(e=>e.gate?.scope===void 0?[]:[{flag:e.gate.flag,scope:e.gate.scope}]);export{N as D,D as E,S as O,$ as R,ze as S,F as W,he as a,ce as b,Ve as c,He as d,C as e,Xe as s,Je as t};
|