@lunora/mcp 1.0.0-alpha.27 → 1.0.0-alpha.270

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE.md +120 -0
  2. package/README.md +250 -14
  3. package/dist/bin.mjs +4 -47
  4. package/dist/docs/index.d.mts +259 -0
  5. package/dist/docs/index.d.ts +259 -0
  6. package/dist/docs/index.mjs +1 -0
  7. package/dist/index.d.mts +77 -226
  8. package/dist/index.d.ts +77 -226
  9. package/dist/index.mjs +1 -5
  10. package/dist/node/index.d.mts +94 -0
  11. package/dist/node/index.d.ts +94 -0
  12. package/dist/node/index.mjs +1 -0
  13. package/dist/packem_shared/AGENT_RUN_INPUT_SCHEMA-BGbKIek4.mjs +1 -0
  14. package/dist/packem_shared/DEFAULT_DOCS_BASE_URL-CiHy_Dbz.mjs +4 -0
  15. package/dist/packem_shared/DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs +1 -0
  16. package/dist/packem_shared/DEFAULT_SEARCH_LIMIT-BMQ6HQ-x.mjs +3 -0
  17. package/dist/packem_shared/DOCS_SERVER_NAME-ClS4cCGm.mjs +1 -0
  18. package/dist/packem_shared/DOCS_URI_SCHEME-DBlxtzS6.mjs +3 -0
  19. package/dist/packem_shared/LOCAL_SERVER_NAME-xQYvyGAB.mjs +1 -0
  20. package/dist/packem_shared/OBSERVABILITY_TOOL_DEFINITIONS-DQ7AUah0.mjs +1 -0
  21. package/dist/packem_shared/READ_ONLY_TOOL_DEFINITIONS-DI9mSjr0.mjs +1 -0
  22. package/dist/packem_shared/compose.d-DiPnHeQv.d.mts +154 -0
  23. package/dist/packem_shared/compose.d-DiPnHeQv.d.ts +154 -0
  24. package/dist/packem_shared/connectFunctionStdio-9qBAqllu.mjs +1 -0
  25. package/dist/packem_shared/connectStdio-w6h0MLdr.mjs +1 -0
  26. package/dist/packem_shared/createAuthedMcpFetchHandler-PpbXKdlq.mjs +1 -0
  27. package/dist/packem_shared/createFunctionMcpServer-CfoMOgf0.mjs +1 -0
  28. package/dist/packem_shared/createLunoraMcpServer-BEsZxiwU.mjs +1 -0
  29. package/dist/packem_shared/createMcpFetchHandler-DsLEboYi.mjs +1 -0
  30. package/dist/packem_shared/createPaidMcpServer-CdDLw3G4.mjs +1 -0
  31. package/dist/packem_shared/createToolServer-CHAjfuNx.mjs +1 -0
  32. package/dist/packem_shared/function-server.d-BoX-fd2B.d.mts +197 -0
  33. package/dist/packem_shared/function-server.d-CnHt2Sb1.d.ts +197 -0
  34. package/dist/packem_shared/package-BXUdl0cu.mjs +1 -0
  35. package/dist/packem_shared/promise-memo-OqVPWoUX.mjs +1 -0
  36. package/dist/packem_shared/serve-stateless.d-DD5arqFx.d.mts +45 -0
  37. package/dist/packem_shared/serve-stateless.d-DD5arqFx.d.ts +45 -0
  38. package/dist/packem_shared/toDocsSearchHits-CBLmtWXt.mjs +1 -0
  39. package/dist/packem_shared/tool-call-Bs-QeKp6.mjs +1 -0
  40. package/dist/packem_shared/tool-result-CPDsNNuJ.mjs +1 -0
  41. package/dist/packem_shared/tools-BMou4kPK.mjs +2 -0
  42. package/dist/worker/index.d.mts +258 -0
  43. package/dist/worker/index.d.ts +258 -0
  44. package/dist/worker/index.mjs +1 -0
  45. package/package.json +27 -5
  46. package/dist/packem_shared/AGENT_RUN_INPUT_SCHEMA-DWobae3P.mjs +0 -168
  47. package/dist/packem_shared/READ_ONLY_TOOL_DEFINITIONS-CWb_wFd5.mjs +0 -204
  48. package/dist/packem_shared/connectStdio-bkJcaXYE.mjs +0 -76
  49. package/dist/packem_shared/createMcpFetchHandler-DfzBSLrm.mjs +0 -14
  50. package/dist/packem_shared/createPaidMcpServer-b-qp_aEF.mjs +0 -93
package/dist/index.d.ts CHANGED
@@ -1,234 +1,85 @@
1
- import { LunoraClient } from '@lunora/client';
2
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
- import '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
4
- import { X402ChargeConfig, X402Price } from '@lunora/x402/charge';
5
- import { Tool } from '@modelcontextprotocol/sdk/types.js';
1
+ export { A as AGENT_RUN_INPUT_SCHEMA, a as AGENT_STATUS_TOOL_NAME,
6
2
  /**
7
- * The tool surface this MCP server exposes. Each tool maps onto a method the
8
- * `LunoraClient` already provides, so an AI agent can introspect a deployment
9
- * (functions, global tables) and invoke its functions over HTTP RPC.
3
+ * `@lunora/mcp` — Model Context Protocol servers for Lunora. This entry exposes
4
+ * a *deployment* to AI agents; the `@lunora/mcp/docs` subpath exposes the
5
+ * framework's *documentation* (credential-free, and safe to host publicly).
10
6
  *
11
- * Definitions and dispatch live here — separate from the server wiring — so the
12
- * behaviour is unit-testable against a mock client without driving a transport.
13
- */
14
- /** A JSON-Schema object describing a tool's arguments, per the MCP spec. */
15
- interface ToolInputSchema {
16
- properties: Record<string, unknown>;
17
- required?: ReadonlyArray<string>;
18
- type: "object";
19
- }
20
- interface ToolDefinition {
21
- description: string;
22
- inputSchema: ToolInputSchema;
23
- name: string;
24
- }
25
- /** The MCP `CallToolResult` shape this server returns. */
26
- interface ToolResult {
27
- content: {
28
- text: string;
29
- type: "text";
30
- }[];
31
- isError?: boolean;
32
- }
33
- /** The read-only tool surface: introspection + query. Always exposed. */
34
- declare const READ_ONLY_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
35
- /** The write tool surface (mutations + actions). Exposed ONLY when writes are enabled. */
36
- declare const WRITE_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
37
- /**
38
- * The tools this server advertises. When `allowWrites` is false (the default),
39
- * only the read-only surface is exposed — the mutation/action tools are omitted
40
- * from `ListTools` entirely, so an AI agent can't invoke a write it can't see.
41
- */
42
- declare const toolDefinitions: (allowWrites: boolean) => ReadonlyArray<ToolDefinition>;
43
- /**
44
- * Dispatch a tool call against `client`. Unknown tools and thrown errors are
45
- * returned as `isError` results (rather than rejections) so the calling model
46
- * sees the failure as tool output, per the MCP convention.
7
+ * The deployment server: It registers tools for introspecting a deployment
8
+ * (`lunora_list_functions`, `lunora_list_tables`) and invoking its functions
9
+ * (`lunora_run_query`, plus `lunora_run_mutation` and `lunora_run_action` when
10
+ * writes are enabled), each backed by `LunoraClient` over HTTP RPC, plus
11
+ * `lunora_explain_error` — a credential-free read of the static error catalog
12
+ * (status, title, hint, matched solution) that needs no deployment at all. It also
13
+ * exposes the deployment's observability reads (`lunora_get_logs`,
14
+ * `lunora_get_issues`, `lunora_get_advisories`, `lunora_get_query_insights`,
15
+ * `lunora_get_migration_status`) when `allowObservability` (or the
16
+ * LUNORA_MCP_ALLOW_OBSERVABILITY env) is set — read-only, but they return
17
+ * production user data, so they are omitted entirely without it. The server is
18
+ * read-only by default — the write tools are exposed only when `allowWrites`
19
+ * (or the `LUNORA_MCP_ALLOW_WRITES` env) is set, and every run tool is
20
+ * allowlisted against the deployment's discovered public functions. Past that
21
+ * gate the two write tools run a two-step confirmation handshake: the first
22
+ * call writes nothing and returns the proposed action plus a self-verifying
23
+ * `actionDigest`, and only a second call carrying `confirmed: true` and that
24
+ * digest executes (see `./write-confirmation`). It can also
25
+ * front durable `@lunora/agent` runs as `agent_<name>` tools when `allowAgents`
26
+ * (or `LUNORA_MCP_ALLOW_AGENTS` + `LUNORA_MCP_AGENTS`) is set. Run the
27
+ * `lunora-mcp` binary (configured via the `LUNORA_URL`, `LUNORA_ADMIN_TOKEN`,
28
+ * and `LUNORA_MCP_ALLOW_WRITES` env vars) for the stdio transport, serve the
29
+ * server remotely over Streamable HTTP with `createMcpFetchHandler` (a
30
+ * Workers-ready `Request` → `Response` handler), or build a server
31
+ * programmatically with `createLunoraMcpServer` and connect any transport.
47
32
  *
48
- * `allowWrites` gates the mutation/action tools: when false (the default) a call
49
- * to a write tool is refused even if the client somehow names it, so the
50
- * read-only guarantee holds at dispatch, not just in the advertised tool list.
51
- */
52
- declare const callTool: (client: LunoraClient, name: string, input: Record<string, unknown>, allowWrites?: boolean) => Promise<ToolResult>;
53
- /**
54
- * Agent exposure for the MCP server: a durable `@lunora/agent` run fronted as an
55
- * MCP tool an external agent can call. The capability boundary is the MCP-server
56
- * process + its token, so WHICH agents are exposed is config on the server (like
57
- * `allowWrites`), not on `defineAgent` — keeping `@lunora/agent` codegen
58
- * byte-identical.
59
- */
60
- interface McpAgentExposure {
61
- /** What the agent does — shown to the calling model, which decides from it. */
62
- description: string;
63
- /** The agent's export name (its `ctx.agents.&lt;name>` / `AGENT_&lt;NAME>` binding). */
64
- name: string;
65
- /** Override the model-facing tool name (default `agent_&lt;name>`). */
66
- toolName?: string;
67
- }
68
- /** The generic status/poll tool advertised alongside the per-agent tools. */
69
- declare const AGENT_STATUS_TOOL_NAME = "lunora_agent_status";
70
- /**
71
- * The uniform input schema every agent tool advertises. Agents share ONE run
72
- * input (`@lunora/agent` has no per-agent validator), so there is nothing to
73
- * derive per agent — a single static schema is reused for every agent tool.
33
+ * A remote endpoint is reachable by anyone who knows its URL, and the tools
34
+ * carry the deployment's admin bearer — so for a public deployment use
35
+ * `createAuthedMcpFetchHandler` instead, which mounts the same server behind
36
+ * better-auth's MCP OAuth gate (`requireMcpAuth` from `@lunora/auth/plugins`)
37
+ * and can scope tool exposure to the access token's own scopes.
74
38
  */
75
- declare const AGENT_RUN_INPUT_SCHEMA: ToolInputSchema;
39
+ type C as CallAgentToolOptions, type F as FunctionMcpServerOptions, type L as LunoraMcpServerOptions,
76
40
  /**
77
- * Parse `LUNORA_MCP_AGENTS` — a `;`-separated list of `name:description` pairs,
78
- * e.g. `"support:Handles support questions;billing:Billing help"`. The
79
- * description may itself contain colons (only the FIRST colon splits). Blank
80
- * entries and entries with an empty name/description are skipped.
81
- */
82
- declare const parseAgentsEnv: (raw: string | undefined) => McpAgentExposure[];
83
- /**
84
- * The tools this module advertises. Fail-closed: only the boolean `true` opts
85
- * in (an env-plumbed caller could pass a truthy string), and the tools appear
86
- * ONLY when at least one agent is exposed — so an agent-free or non-opted-in
87
- * server never lists them.
88
- */
89
- declare const agentToolDefinitions: (exposures: ReadonlyArray<McpAgentExposure>, allowAgents: boolean) => ReadonlyArray<ToolDefinition>;
90
- /** Options threaded into a single agent tool dispatch. */
91
- interface CallAgentToolOptions {
92
- /** Opt-in gate — must be exactly `true` or the call is refused fail-closed. */
93
- allowAgents: boolean;
94
- /** The exposures advertised by this server. */
95
- exposures: ReadonlyArray<McpAgentExposure>;
96
- /** Wall-clock budget a single call awaits before returning a pending result. */
97
- maxWaitMs?: number;
98
- /** Delay between thread-status polls. */
99
- pollIntervalMs?: number;
100
- /** Test seam replacing the between-poll wait; production uses a real timer. */
101
- wait?: (ms: number) => Promise<void>;
102
- }
103
- /**
104
- * Dispatch an agent tool call: start a durable run via `agents:agentRun`, then
105
- * await-with-timeout — poll `agents:agentThread` until terminal (returning the
106
- * final answer from `agents:agentMessages`) or, on budget exhaustion, return a
107
- * NON-error pending payload the caller resumes with `lunora_agent_status`.
41
+ * `@lunora/mcp` — Model Context Protocol servers for Lunora. This entry exposes
42
+ * a *deployment* to AI agents; the `@lunora/mcp/docs` subpath exposes the
43
+ * framework's *documentation* (credential-free, and safe to host publicly).
108
44
  *
109
- * Fail-closed: refused at dispatch unless `allowAgents === true`, mirroring the
110
- * `allowWrites` guard — starting a run is a side effect and must not ride the
111
- * read-only default.
112
- */
113
- declare const callAgentTool: (client: LunoraClient, name: string, input: Record<string, unknown>, options: CallAgentToolOptions) => Promise<ToolResult>;
114
- interface LunoraMcpServerOptions {
115
- /** Wall-clock budget a single agent tool call awaits before returning a pending result. */
116
- agentMaxWaitMs?: number;
117
- /** Delay between agent thread-status polls. */
118
- agentPollIntervalMs?: number;
119
- /** The agents this server fronts as MCP tools (see `allowAgents`). */
120
- agents?: ReadonlyArray<McpAgentExposure>;
121
- /**
122
- * Expose the per-agent tools (`agent_&lt;name>` + the generic
123
- * `lunora_agent_status`). Defaults to `false`, mirroring `allowWrites`:
124
- * starting a durable agent run is a side effect, so the agent tools are
125
- * omitted from the advertised list AND refused at dispatch unless explicitly
126
- * opted in. Only takes effect together with a non-empty `agents` list.
127
- */
128
- allowAgents?: boolean;
129
- /**
130
- * Expose the write tools (`lunora_run_mutation` / `lunora_run_action`).
131
- * Defaults to `false`: the server is READ-ONLY unless explicitly opted in,
132
- * so a prompt-injected or misaligned agent can't mutate the deployment with
133
- * the configured token. When false the write tools are omitted from the
134
- * advertised tool list AND refused at dispatch.
135
- */
136
- allowWrites?: boolean;
137
- /**
138
- * Pre-built client (test injection). When omitted a `LunoraClient` is
139
- * created from `url`/`token`/`fetch`.
140
- */
141
- client?: LunoraClient;
142
- /** `fetch` implementation; defaults to the ambient global. */
143
- fetch?: typeof fetch;
144
- /**
145
- * Bearer token sent on every RPC. This must be the deployment's **admin
146
- * bearer**: the introspection/allowlist path every tool depends on
147
- * (`lunora_list_functions`, `lunora_list_tables`, and the `assertRunnable`
148
- * precheck that runs before every `run` tool) hits admin-gated
149
- * `/_lunora/admin/*` routes, so no scoped/app token works today — it would
150
- * 403 (`ADMIN_FORBIDDEN`) on the first tool call. The read-only guarantee is
151
- * therefore NOT enforced by the token's scope; it is enforced in-process via
152
- * `allowWrites: false` (the default), which omits the write tools from the
153
- * advertised list and refuses them at dispatch.
154
- */
155
- token?: string;
156
- /** Base URL of the deployed Lunora Worker. Required unless `client` is given. */
157
- url?: string;
158
- }
159
- /**
160
- * Build an MCP `Server` whose tools talk to a Lunora deployment. The server is
161
- * transport-agnostic — call `.connect(transport)` yourself, or use
162
- * `connectStdio` for the common stdio case.
45
+ * The deployment server: It registers tools for introspecting a deployment
46
+ * (`lunora_list_functions`, `lunora_list_tables`) and invoking its functions
47
+ * (`lunora_run_query`, plus `lunora_run_mutation` and `lunora_run_action` when
48
+ * writes are enabled), each backed by `LunoraClient` over HTTP RPC, plus
49
+ * `lunora_explain_error` — a credential-free read of the static error catalog
50
+ * (status, title, hint, matched solution) that needs no deployment at all. It also
51
+ * exposes the deployment's observability reads (`lunora_get_logs`,
52
+ * `lunora_get_issues`, `lunora_get_advisories`, `lunora_get_query_insights`,
53
+ * `lunora_get_migration_status`) when `allowObservability` (or the
54
+ * LUNORA_MCP_ALLOW_OBSERVABILITY env) is set — read-only, but they return
55
+ * production user data, so they are omitted entirely without it. The server is
56
+ * read-only by default — the write tools are exposed only when `allowWrites`
57
+ * (or the `LUNORA_MCP_ALLOW_WRITES` env) is set, and every run tool is
58
+ * allowlisted against the deployment's discovered public functions. Past that
59
+ * gate the two write tools run a two-step confirmation handshake: the first
60
+ * call writes nothing and returns the proposed action plus a self-verifying
61
+ * `actionDigest`, and only a second call carrying `confirmed: true` and that
62
+ * digest executes (see `./write-confirmation`). It can also
63
+ * front durable `@lunora/agent` runs as `agent_<name>` tools when `allowAgents`
64
+ * (or `LUNORA_MCP_ALLOW_AGENTS` + `LUNORA_MCP_AGENTS`) is set. Run the
65
+ * `lunora-mcp` binary (configured via the `LUNORA_URL`, `LUNORA_ADMIN_TOKEN`,
66
+ * and `LUNORA_MCP_ALLOW_WRITES` env vars) for the stdio transport, serve the
67
+ * server remotely over Streamable HTTP with `createMcpFetchHandler` (a
68
+ * Workers-ready `Request` → `Response` handler), or build a server
69
+ * programmatically with `createLunoraMcpServer` and connect any transport.
163
70
  *
164
- * Tool calls are dispatched through `callTool`, which the deployment reaches
165
- * over HTTP RPC. No WebSocket is opened (the tools never subscribe), so this is
166
- * safe to run as a short-lived stdio process.
71
+ * A remote endpoint is reachable by anyone who knows its URL, and the tools
72
+ * carry the deployment's admin bearer — so for a public deployment use
73
+ * `createAuthedMcpFetchHandler` instead, which mounts the same server behind
74
+ * better-auth's MCP OAuth gate (`requireMcpAuth` from `@lunora/auth/plugins`)
75
+ * and can scope tool exposure to the access token's own scopes.
167
76
  */
168
- declare const createLunoraMcpServer: (options: LunoraMcpServerOptions) => Server;
169
- /**
170
- * Build the server and connect it over stdio — the transport MCP clients use
171
- * when they spawn the `lunora-mcp` binary. Resolves once the transport is
172
- * connected; the process then stays alive serving requests.
173
- */
174
- declare const connectStdio: (options: LunoraMcpServerOptions) => Promise<Server>;
175
- /** A Web-Standard fetch handler: takes a `Request`, returns the MCP `Response`. */
176
- type McpFetchHandler = (request: Request) => Promise<Response>;
177
- /**
178
- * Build a stateless Streamable-HTTP fetch handler for a Lunora MCP server. Each
179
- * invocation constructs a fresh proxy server and serves the request through
180
- * {@link serveStateless}.
181
- */
182
- declare const createMcpFetchHandler: (options: LunoraMcpServerOptions) => McpFetchHandler;
183
- /** A tool handler: receives the call's `arguments` bag, returns an MCP tool result. */
184
- type ToolHandler = (arguments_: Record<string, unknown>) => Promise<ToolResult> | ToolResult;
185
- /** Registration shape for a free tool. */
186
- interface RegisterToolOptions {
187
- /** Optional MCP tool annotations (`readOnlyHint`, `title`, …). */
188
- annotations?: Tool["annotations"];
189
- /** Human/model-facing description of what the tool does. */
190
- description: string;
191
- /** JSON-Schema object describing the tool's arguments. */
192
- inputSchema: ToolInputSchema;
193
- /** Unique tool name (the MCP `tools/call` `name`). */
194
- name: string;
195
- }
196
- /** Registration shape for a paid tool: a {@link RegisterToolOptions} plus its USD price. */
197
- interface RegisterPaidToolOptions extends RegisterToolOptions {
198
- /** USD price per call (e.g. `"$0.05"`), charged via x402 before dispatch. */
199
- price: X402Price;
200
- }
201
- /** x402 settlement vocabulary shared by every paid tool (network, recipient, facilitator); price is per-tool. */
202
- type PaidMcpChargeConfig = Omit<X402ChargeConfig, "price">;
203
- /** Config for `createPaidMcpServer`. */
204
- interface PaidMcpServerConfig {
205
- /** The worker-level x402 charge config; each paid tool supplies only its own `price`. */
206
- charge: PaidMcpChargeConfig;
207
- /** Name/version advertised in the MCP `initialize` handshake. Defaults to `lunora-paid-mcp`. */
208
- serverInfo?: {
209
- name: string;
210
- version: string;
211
- };
212
- }
213
- /** A paid MCP server: register free/paid tools, then serve over Streamable HTTP. */
214
- interface PaidMcpServer {
215
- /** The Streamable-HTTP fetch handler; gates each paid `tools/call` behind x402. */
216
- readonly fetchHandler: McpFetchHandler;
217
- /** Register a **paid** tool: its dispatch runs the x402 charge middleware first. */
218
- paidTool: (options: RegisterPaidToolOptions, handler: ToolHandler) => void;
219
- /** Register a **free** tool (coexists with paid tools on the same server). */
220
- tool: (options: RegisterToolOptions, handler: ToolHandler) => void;
221
- }
222
- /**
223
- * Create a paid MCP server. Register free tools with `tool()` and priced tools
224
- * with `paidTool()` (they coexist), then serve `fetchHandler` over HTTP.
225
- *
226
- * The server is **stateless**: `fetchHandler` builds a fresh `Server` per
227
- * request (reading the live tool registry), so tools registered before the
228
- * first request are all visible. Each priced tool memoises one initialised
229
- * `ChargeMiddleware` (keyed by tool name, baking that tool's price and naming
230
- * the tool as the challenge `resource`); a failed init is not cached, so a
231
- * transient facilitator outage retries on the next call.
232
- */
233
- declare const createPaidMcpServer: (config: PaidMcpServerConfig) => PaidMcpServer;
234
- export { AGENT_RUN_INPUT_SCHEMA, AGENT_STATUS_TOOL_NAME, type CallAgentToolOptions, type LunoraMcpServerOptions, type McpAgentExposure, type McpFetchHandler, type PaidMcpChargeConfig, type PaidMcpServer, type PaidMcpServerConfig, READ_ONLY_TOOL_DEFINITIONS, type RegisterPaidToolOptions, type RegisterToolOptions, type ToolDefinition, type ToolHandler, type ToolInputSchema, type ToolResult, WRITE_TOOL_DEFINITIONS, agentToolDefinitions, callAgentTool, callTool, connectStdio, createLunoraMcpServer, createMcpFetchHandler, createPaidMcpServer, parseAgentsEnv, toolDefinitions };
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-CnHt2Sb1.js";
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-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
+ 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
+ import '@lunora/client/admin';
83
+ import '@modelcontextprotocol/sdk/server/index.js';
84
+ import '@lunora/client';
85
+ import '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
package/dist/index.mjs CHANGED
@@ -1,5 +1 @@
1
- export { AGENT_RUN_INPUT_SCHEMA, AGENT_STATUS_TOOL_NAME, agentToolDefinitions, callAgentTool, parseAgentsEnv } from './packem_shared/AGENT_RUN_INPUT_SCHEMA-DWobae3P.mjs';
2
- export { createMcpFetchHandler } from './packem_shared/createMcpFetchHandler-DfzBSLrm.mjs';
3
- export { createPaidMcpServer } from './packem_shared/createPaidMcpServer-b-qp_aEF.mjs';
4
- export { connectStdio, createLunoraMcpServer } from './packem_shared/connectStdio-bkJcaXYE.mjs';
5
- export { READ_ONLY_TOOL_DEFINITIONS, WRITE_TOOL_DEFINITIONS, callTool, toolDefinitions } from './packem_shared/READ_ONLY_TOOL_DEFINITIONS-CWb_wFd5.mjs';
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-PpbXKdlq.mjs";import{createToolServer as _}from"./packem_shared/createToolServer-CHAjfuNx.mjs";import{createFunctionMcpServer as f}from"./packem_shared/createFunctionMcpServer-CfoMOgf0.mjs";import{default as s}from"./packem_shared/connectFunctionStdio-9qBAqllu.mjs";import{createMcpFetchHandler as N}from"./packem_shared/createMcpFetchHandler-DsLEboYi.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-xQYvyGAB.mjs";import{createPaidMcpServer as D}from"./packem_shared/createPaidMcpServer-CdDLw3G4.mjs";import{createLunoraMcpServer as R}from"./packem_shared/createLunoraMcpServer-BEsZxiwU.mjs";import{default as u}from"./packem_shared/connectStdio-w6h0MLdr.mjs";import{R as Y,W as g,c as h,t as B}from"./packem_shared/tools-BMou4kPK.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};
@@ -0,0 +1,94 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import { F as FunctionMcpServerOptions, L as LunoraMcpServerOptions } from "../packem_shared/function-server.d-BoX-fd2B.mjs";
3
+ export { e as createLunoraMcpServer } from "../packem_shared/function-server.d-BoX-fd2B.mjs";
4
+ import { LunoraAdminClient } from '@lunora/client/admin';
5
+ import { a as McpTool } from "../packem_shared/compose.d-DiPnHeQv.mjs";
6
+ import '@lunora/client';
7
+ /**
8
+ * Build a per-function server and connect it over stdio, the transport an editor
9
+ * spawns. Resolves once the transport is connected; the process then stays alive
10
+ * serving requests. Lives apart from `./stdio` for the same reason that module
11
+ * does: the Worker entry's module graph never pulls in the stdio transport.
12
+ */
13
+ declare const connectFunctionStdio: (options: FunctionMcpServerOptions) => Promise<Server>;
14
+ /** A Lunora deployment the tools dispatch against. */
15
+ interface LocalDeployment {
16
+ token?: string;
17
+ url: string;
18
+ }
19
+ /**
20
+ * Where the deployment comes from: a fixed value, or a function consulted on
21
+ * every tool call.
22
+ *
23
+ * The resolver form exists because an editor spawns this server when the
24
+ * project opens — routinely *before* `lunora dev` is running, and it keeps the
25
+ * process alive across every restart afterwards. A URL captured once at startup
26
+ * would therefore be absent for the entire first session and stale after the
27
+ * first restart.
28
+ */
29
+ type LocalDeploymentSource = (() => LocalDeployment | undefined) | LocalDeployment;
30
+ interface LocalMcpServerOptions {
31
+ /**
32
+ * Expose the deployment write tools (`lunora_run_mutation` /
33
+ * `lunora_run_action`). Defaults to `false` — the same fail-closed default
34
+ * as the remote server. Locally the blast radius is dev data rather than
35
+ * production, but a mutation is still a side effect an agent should be
36
+ * granted deliberately.
37
+ */
38
+ allowWrites?: boolean;
39
+ /**
40
+ * The Lunora deployment (usually the running dev server) to expose. Omit to
41
+ * leave the deployment tools out entirely.
42
+ */
43
+ deployment?: LocalDeploymentSource;
44
+ /** Docs site origin backing the documentation tools; `false` omits them. */
45
+ docs?: false | {
46
+ baseUrl?: string;
47
+ };
48
+ /** Extra tools to compose in, e.g. the CLI's local dev-server tools. */
49
+ extraTools?: ReadonlyArray<McpTool>;
50
+ /** `fetch` implementation; defaults to the ambient global. */
51
+ fetch?: typeof fetch;
52
+ /** Version reported in the MCP handshake — the host CLI's, not this package's. */
53
+ version?: string;
54
+ }
55
+ /** Server identity advertised in the MCP `initialize` handshake. */
56
+ declare const LOCAL_SERVER_NAME = "lunora";
57
+ /** Shown when a deployment tool is called and no dev server can be found. */
58
+ declare const NO_DEPLOYMENT_MESSAGE = "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).";
59
+ /**
60
+ * Assemble the tool list, in the order it is advertised: docs first (the
61
+ * surface that always works), then the caller's extras, then the error catalog
62
+ * (compiled in, so it needs no deployment either), then the deployment tools.
63
+ * Order also decides precedence — `createToolServer` keeps the first
64
+ * registration of a duplicated name.
65
+ *
66
+ * `clientFor` is the shared client cache built once by
67
+ * {@link createLocalMcpServer} and threaded into both the tool and resource
68
+ * surfaces. Exported (and called directly by tests) without going through
69
+ * `createLocalMcpServer`, so a caller that omits it gets a private,
70
+ * call-scoped cache — same shape as before this surface was shared, just
71
+ * without the cross-surface sharing that only matters once a resource
72
+ * surface exists alongside it.
73
+ */
74
+ declare const localTools: (options: LocalMcpServerOptions, clientFor?: (deployment: LocalDeployment) => LunoraAdminClient) => ReadonlyArray<McpTool>;
75
+ /** Build the composed local server without connecting a transport. */
76
+ declare const createLocalMcpServer: (options?: LocalMcpServerOptions) => Server;
77
+ /**
78
+ * Build the composed local server and connect it over stdio — the transport an
79
+ * MCP client uses when it spawns `lunora mcp serve`. Resolves once connected;
80
+ * the process then stays alive serving requests.
81
+ */
82
+ declare const connectLocalStdio: (options?: LocalMcpServerOptions) => Promise<Server>;
83
+ /**
84
+ * Build the server and connect it over stdio — the transport MCP clients use
85
+ * when they spawn the `lunora-mcp` binary. Resolves once the transport is
86
+ * connected; the process then stays alive serving requests.
87
+ *
88
+ * Lives apart from `server.ts` so the Worker entry's module graph never pulls
89
+ * in the stdio transport (and its `node:process` import).
90
+ */
91
+ declare const connectStdio: (options: LunoraMcpServerOptions) => Promise<Server>;
92
+ export { LOCAL_SERVER_NAME, type LocalDeployment, type LocalDeploymentSource, type LocalMcpServerOptions, type LunoraMcpServerOptions, NO_DEPLOYMENT_MESSAGE,
93
+ /** Node-only entry: the stdio transport and the local/deployment servers. */
94
+ connectFunctionStdio, connectLocalStdio, connectStdio, createLocalMcpServer, localTools };
@@ -0,0 +1,94 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import { F as FunctionMcpServerOptions, L as LunoraMcpServerOptions } from "../packem_shared/function-server.d-CnHt2Sb1.js";
3
+ export { e as createLunoraMcpServer } from "../packem_shared/function-server.d-CnHt2Sb1.js";
4
+ import { LunoraAdminClient } from '@lunora/client/admin';
5
+ import { a as McpTool } from "../packem_shared/compose.d-DiPnHeQv.js";
6
+ import '@lunora/client';
7
+ /**
8
+ * Build a per-function server and connect it over stdio, the transport an editor
9
+ * spawns. Resolves once the transport is connected; the process then stays alive
10
+ * serving requests. Lives apart from `./stdio` for the same reason that module
11
+ * does: the Worker entry's module graph never pulls in the stdio transport.
12
+ */
13
+ declare const connectFunctionStdio: (options: FunctionMcpServerOptions) => Promise<Server>;
14
+ /** A Lunora deployment the tools dispatch against. */
15
+ interface LocalDeployment {
16
+ token?: string;
17
+ url: string;
18
+ }
19
+ /**
20
+ * Where the deployment comes from: a fixed value, or a function consulted on
21
+ * every tool call.
22
+ *
23
+ * The resolver form exists because an editor spawns this server when the
24
+ * project opens — routinely *before* `lunora dev` is running, and it keeps the
25
+ * process alive across every restart afterwards. A URL captured once at startup
26
+ * would therefore be absent for the entire first session and stale after the
27
+ * first restart.
28
+ */
29
+ type LocalDeploymentSource = (() => LocalDeployment | undefined) | LocalDeployment;
30
+ interface LocalMcpServerOptions {
31
+ /**
32
+ * Expose the deployment write tools (`lunora_run_mutation` /
33
+ * `lunora_run_action`). Defaults to `false` — the same fail-closed default
34
+ * as the remote server. Locally the blast radius is dev data rather than
35
+ * production, but a mutation is still a side effect an agent should be
36
+ * granted deliberately.
37
+ */
38
+ allowWrites?: boolean;
39
+ /**
40
+ * The Lunora deployment (usually the running dev server) to expose. Omit to
41
+ * leave the deployment tools out entirely.
42
+ */
43
+ deployment?: LocalDeploymentSource;
44
+ /** Docs site origin backing the documentation tools; `false` omits them. */
45
+ docs?: false | {
46
+ baseUrl?: string;
47
+ };
48
+ /** Extra tools to compose in, e.g. the CLI's local dev-server tools. */
49
+ extraTools?: ReadonlyArray<McpTool>;
50
+ /** `fetch` implementation; defaults to the ambient global. */
51
+ fetch?: typeof fetch;
52
+ /** Version reported in the MCP handshake — the host CLI's, not this package's. */
53
+ version?: string;
54
+ }
55
+ /** Server identity advertised in the MCP `initialize` handshake. */
56
+ declare const LOCAL_SERVER_NAME = "lunora";
57
+ /** Shown when a deployment tool is called and no dev server can be found. */
58
+ declare const NO_DEPLOYMENT_MESSAGE = "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).";
59
+ /**
60
+ * Assemble the tool list, in the order it is advertised: docs first (the
61
+ * surface that always works), then the caller's extras, then the error catalog
62
+ * (compiled in, so it needs no deployment either), then the deployment tools.
63
+ * Order also decides precedence — `createToolServer` keeps the first
64
+ * registration of a duplicated name.
65
+ *
66
+ * `clientFor` is the shared client cache built once by
67
+ * {@link createLocalMcpServer} and threaded into both the tool and resource
68
+ * surfaces. Exported (and called directly by tests) without going through
69
+ * `createLocalMcpServer`, so a caller that omits it gets a private,
70
+ * call-scoped cache — same shape as before this surface was shared, just
71
+ * without the cross-surface sharing that only matters once a resource
72
+ * surface exists alongside it.
73
+ */
74
+ declare const localTools: (options: LocalMcpServerOptions, clientFor?: (deployment: LocalDeployment) => LunoraAdminClient) => ReadonlyArray<McpTool>;
75
+ /** Build the composed local server without connecting a transport. */
76
+ declare const createLocalMcpServer: (options?: LocalMcpServerOptions) => Server;
77
+ /**
78
+ * Build the composed local server and connect it over stdio — the transport an
79
+ * MCP client uses when it spawns `lunora mcp serve`. Resolves once connected;
80
+ * the process then stays alive serving requests.
81
+ */
82
+ declare const connectLocalStdio: (options?: LocalMcpServerOptions) => Promise<Server>;
83
+ /**
84
+ * Build the server and connect it over stdio — the transport MCP clients use
85
+ * when they spawn the `lunora-mcp` binary. Resolves once the transport is
86
+ * connected; the process then stays alive serving requests.
87
+ *
88
+ * Lives apart from `server.ts` so the Worker entry's module graph never pulls
89
+ * in the stdio transport (and its `node:process` import).
90
+ */
91
+ declare const connectStdio: (options: LunoraMcpServerOptions) => Promise<Server>;
92
+ export { LOCAL_SERVER_NAME, type LocalDeployment, type LocalDeploymentSource, type LocalMcpServerOptions, type LunoraMcpServerOptions, NO_DEPLOYMENT_MESSAGE,
93
+ /** Node-only entry: the stdio transport and the local/deployment servers. */
94
+ connectFunctionStdio, connectLocalStdio, connectStdio, createLocalMcpServer, localTools };
@@ -0,0 +1 @@
1
+ import{default as r}from"../packem_shared/connectFunctionStdio-9qBAqllu.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-xQYvyGAB.mjs";import{createLunoraMcpServer as f}from"../packem_shared/createLunoraMcpServer-BEsZxiwU.mjs";import{default as L}from"../packem_shared/connectStdio-w6h0MLdr.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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1,4 @@
1
+ import{toDocsSearchHits as h}from"./toDocsSearchHits-CBLmtWXt.mjs";const f="https://lunora.sh",u=1e4,m=t=>t.endsWith("/")?t.slice(0,-1):t,p="\\",g=(t,n,i)=>{for(let s=i;s<t.length;s+=1)if(t[s]===n&&t[s-1]!==p)return s;return-1},d=t=>t.replaceAll(String.raw`\[`,"[").replaceAll(String.raw`\]`,"]").replaceAll(String.raw`\(`,"(").replaceAll(String.raw`\)`,")"),S=t=>{const n=t.trim();if(!n.startsWith("- ["))return;const i=n.lastIndexOf("](");if(i===-1)return;const s=g(n,")",i+2);if(s===-1)return;const o=d(n.slice(3,i).trim()),c=d(n.slice(i+2,s).trim());if(o.length===0||c.length===0)return;const e=n.slice(s+1).trim(),r=e.startsWith(":")?e.slice(1).trim():"";return r.length>0?{description:r,title:o,url:c}:{title:o,url:c}},x=t=>{if(!t.endsWith(")"))return t;const n=t.lastIndexOf(" (");if(n===-1)return t;const i=t.slice(n+2,-1);return i.startsWith("/")||i.startsWith("http")?t.slice(0,n).trim():t},y=(t,n)=>{for(const i of t.split(`
2
+ `)){if(i.startsWith("# "))return x(i.slice(2).trim());if(i.trim().length>0)break}return n},b=t=>{if(!t.startsWith("# "))return t;const n=t.indexOf(`
3
+ `);return n===-1?"":t.slice(n+1).trimStart()},A=(t={})=>{const n=m(t.baseUrl??f),i=t.fetch??globalThis.fetch,s=t.timeoutMs??u,o=async e=>{try{const r=await i(`${n}${e}`,{headers:{accept:"text/plain, application/json"},signal:AbortSignal.timeout(s)});return r.ok?{body:await r.text()}:{missing:!0}}catch(r){return{unreachable:r instanceof Error?r.message:String(r)}}},c=(e,r)=>{if("unreachable"in e)throw new Error(`could not reach the documentation site at ${n}${r}: ${e.unreachable}`);return"missing"in e?void 0:e.body};return{getPage:async e=>{const r=c(await o(`/llms.mdx${e}`),`/llms.mdx${e}`);if(!(r===void 0||r.trim().length===0))return{content:b(r),title:y(r,e),url:e}},listPages:async()=>{const e=c(await o("/llms.txt"),"/llms.txt");if(e===void 0)return[];const r=[];for(const l of e.split(`
4
+ `)){const a=S(l);a!==void 0&&r.push(a)}return r},search:async e=>{const r=`/api/search?query=${encodeURIComponent(e)}`,l=c(await o(r),r);if(l===void 0)return[];let a;try{a=JSON.parse(l)}catch{return[]}return Array.isArray(a)?h(a):[]}}};export{f as DEFAULT_DOCS_BASE_URL,A as createRemoteDocsIndex,S as parseIndexLine};
@@ -0,0 +1 @@
1
+ import{WebStandardStreamableHTTPServerTransport as y}from"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";const u=128*1024,p=e=>e!==void 0&&Number.isSafeInteger(e)&&e>=0?e:u,l=async(e,t)=>{if(!e.body)return"";const r=e.body.getReader(),s=new TextDecoder;let n=0,o="";for(;;){const{done:i,value:a}=await r.read();if(i)break;if(a){if(n+=a.byteLength,n>t){r.cancel().catch(()=>{});return}o+=s.decode(a,{stream:!0})}}return o+s.decode()},d=(e,t,r)=>Response.json({error:{code:t,message:r},id:null,jsonrpc:"2.0"},{status:e}),c=()=>d(400,-32600,"batched requests are not supported: send one JSON-RPC message per request"),f=async(e,t)=>{if(e.method!=="POST")return{parsedBody:void 0};const r=p(t),s={response:d(413,-32600,`request body exceeds ${String(r)} bytes`)},n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>r)return s;const o=await l(e,r);if(o===void 0)return s;try{return{parsedBody:JSON.parse(o)}}catch{return{response:d(400,-32700,"parse error: body is not valid JSON")}}},b=async(e,t)=>{if(e.method!=="POST")return{parsedBody:t?.parsedBody};if(t?.parsedBody!==void 0)return Array.isArray(t.parsedBody)?{response:c()}:{parsedBody:t.parsedBody};const r=await f(e,t?.maxRequestBytes);return"response"in r?r:Array.isArray(r.parsedBody)?{response:c()}:r},B=async(e,t,r)=>{const s=await b(t,r);if("response"in s)return s.response;const n=new y({enableJsonResponse:!0,sessionIdGenerator:void 0});try{return await e.connect(n),await n.handleRequest(t,{authInfo:r?.authInfo,parsedBody:s.parsedBody})}finally{n.close().catch(()=>{}),e.close().catch(()=>{})}};export{u as DEFAULT_MAX_REQUEST_BYTES,f as readScreenedBody,B as serveStateless};
@@ -0,0 +1,3 @@
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
+
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1,3 @@
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
+
3
+ ${r.content}`}}});export{e as DOCS_URI_SCHEME,d as docsResources,c as fromDocsUri,n as toDocsUri};
@@ -0,0 +1 @@
1
+ import{LunoraAdminClient as m}from"@lunora/client/admin";import{StdioServerTransport as f}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-BMou4kPK.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).",A=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 m({fetch:e,url:t.url});return t.token!==void 0&&t.token.length>0&&o.setAuthToken(t.token),p(n,A),n.set(r,o),o}},i=e=>e?.token!==void 0&&e.token.length>0,g=(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(...g(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 f),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};
@@ -0,0 +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-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-BMou4kPK.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};