@lunora/mcp 1.0.0-alpha.23 → 1.0.0-alpha.231

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 (36) hide show
  1. package/LICENSE.md +120 -0
  2. package/README.md +200 -14
  3. package/dist/bin.mjs +4 -47
  4. package/dist/docs/index.d.mts +258 -0
  5. package/dist/docs/index.d.ts +258 -0
  6. package/dist/docs/index.mjs +1 -0
  7. package/dist/index.d.mts +507 -26
  8. package/dist/index.d.ts +507 -26
  9. package/dist/index.mjs +1 -5
  10. package/dist/packem_shared/AGENT_RUN_INPUT_SCHEMA-hKbpa3Dg.mjs +1 -0
  11. package/dist/packem_shared/DEFAULT_DOCS_BASE_URL-CiHy_Dbz.mjs +4 -0
  12. package/dist/packem_shared/DEFAULT_MAX_REQUEST_BYTES-CbbpkHRK.mjs +1 -0
  13. package/dist/packem_shared/DEFAULT_SEARCH_LIMIT-B8C5JM2y.mjs +3 -0
  14. package/dist/packem_shared/DOCS_SERVER_NAME-CUnLrk1a.mjs +1 -0
  15. package/dist/packem_shared/DOCS_URI_SCHEME-C35UQ5Fo.mjs +3 -0
  16. package/dist/packem_shared/LOCAL_SERVER_NAME-DM_NJ-eY.mjs +1 -0
  17. package/dist/packem_shared/OBSERVABILITY_TOOL_DEFINITIONS-mO4JuHgV.mjs +1 -0
  18. package/dist/packem_shared/READ_ONLY_TOOL_DEFINITIONS-DA4wD25I.mjs +1 -0
  19. package/dist/packem_shared/connectStdio-n-RHjcwN.mjs +1 -0
  20. package/dist/packem_shared/createAuthedMcpFetchHandler-DUHhAwgo.mjs +1 -0
  21. package/dist/packem_shared/createMcpFetchHandler-CNEfLA-N.mjs +1 -0
  22. package/dist/packem_shared/createPaidMcpServer-C_V1beyQ.mjs +1 -0
  23. package/dist/packem_shared/createToolServer-BtGuPyMU.mjs +1 -0
  24. package/dist/packem_shared/observability-tools-D4Z8dGS-.mjs +1 -0
  25. package/dist/packem_shared/promise-memo-OqVPWoUX.mjs +1 -0
  26. package/dist/packem_shared/serve-stateless.d-CKsbI0fP.d.mts +154 -0
  27. package/dist/packem_shared/serve-stateless.d-CKsbI0fP.d.ts +154 -0
  28. package/dist/packem_shared/toDocsSearchHits-CBLmtWXt.mjs +1 -0
  29. package/dist/packem_shared/tool-call-Bs-QeKp6.mjs +1 -0
  30. package/dist/packem_shared/tools-Dmnb3M2T.mjs +2 -0
  31. package/package.json +18 -5
  32. package/dist/packem_shared/AGENT_RUN_INPUT_SCHEMA-DWobae3P.mjs +0 -168
  33. package/dist/packem_shared/READ_ONLY_TOOL_DEFINITIONS-CWb_wFd5.mjs +0 -204
  34. package/dist/packem_shared/connectStdio-bkJcaXYE.mjs +0 -76
  35. package/dist/packem_shared/createMcpFetchHandler-DfzBSLrm.mjs +0 -14
  36. package/dist/packem_shared/createPaidMcpServer-b-qp_aEF.mjs +0 -93
package/dist/index.d.mts CHANGED
@@ -1,83 +1,564 @@
1
1
  import { LunoraClient } from '@lunora/client';
2
+ import { T as ToolDefinition, f as ToolResult, e as ToolInputSchema, a as McpFetchHandler, b as McpTool } from "./packem_shared/serve-stateless.d-CKsbI0fP.mjs";
3
+ export { D as DEFAULT_MAX_REQUEST_BYTES, type d as McpServerInfo, type S as ServeStatelessOptions, g as createToolServer, s as serveStateless } from "./packem_shared/serve-stateless.d-CKsbI0fP.mjs";
2
4
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
- import '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
4
- import { X402ChargeConfig, X402Price } from '@lunora/x402/charge';
5
5
  import { Tool } from '@modelcontextprotocol/sdk/types.js';
6
- interface ToolInputSchema {
7
- properties: Record<string, unknown>;
8
- required?: ReadonlyArray<string>;
9
- type: "object";
10
- }
11
- interface ToolDefinition {
12
- description: string;
13
- inputSchema: ToolInputSchema;
14
- name: string;
15
- }
16
- interface ToolResult {
17
- content: {
18
- text: string;
19
- type: "text";
20
- }[];
21
- isError?: boolean;
22
- }
6
+ import '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
7
+ /**
8
+ * The observability tools. Descriptions say WHEN to call the tool, not just
9
+ * what it returns — an agent picking between five similar reads needs the
10
+ * trigger, and it pays for these strings on every turn.
11
+ */
12
+ declare const OBSERVABILITY_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
13
+ /** The read-only tool surface: introspection + query. Always exposed. */
23
14
  declare const READ_ONLY_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
15
+ /** The write tool surface (mutations + actions). Exposed ONLY when writes are enabled. */
24
16
  declare const WRITE_TOOL_DEFINITIONS: ReadonlyArray<ToolDefinition>;
25
- declare const toolDefinitions: (allowWrites: boolean) => ReadonlyArray<ToolDefinition>;
26
- declare const callTool: (client: LunoraClient, name: string, input: Record<string, unknown>, allowWrites?: boolean) => Promise<ToolResult>;
17
+ /**
18
+ * The tools this server advertises: every family whose gate is open, in table
19
+ * order. A gated family is OMITTED rather than refused — an AI agent can't
20
+ * invoke what it can't see — and {@link callTool} re-checks the same gate at
21
+ * dispatch, so the guarantee does not depend on a client honouring this list.
22
+ */
23
+ declare const toolDefinitions: (allowWrites: boolean, allowObservability?: boolean, allowDataReads?: boolean) => ReadonlyArray<ToolDefinition>;
24
+ /**
25
+ * Dispatch a tool call against `client`: find the family that owns `name`, check
26
+ * its gate, hand off. Unknown tools and thrown errors are returned as `isError`
27
+ * results (rather than rejections) so the calling model sees the failure as tool
28
+ * output, per the MCP convention.
29
+ *
30
+ * Each gate is enforced HERE as well as in {@link toolDefinitions}, so a call to
31
+ * a gated tool is refused even if the client somehow names one it was never
32
+ * shown.
33
+ */
34
+ declare const callTool: (client: LunoraClient, name: string, input: Record<string, unknown>, allowWrites?: boolean, allowObservability?: boolean, allowDataReads?: boolean) => Promise<ToolResult>;
35
+ /**
36
+ * Agent exposure for the MCP server: a durable `@lunora/agent` run fronted as an
37
+ * MCP tool an external agent can call. The capability boundary is the MCP-server
38
+ * process + its token, so WHICH agents are exposed is config on the server (like
39
+ * `allowWrites`), not on `defineAgent` — keeping `@lunora/agent` codegen
40
+ * byte-identical.
41
+ */
27
42
  interface McpAgentExposure {
43
+ /** What the agent does — shown to the calling model, which decides from it. */
28
44
  description: string;
45
+ /** The agent's export name (its `ctx.agents.<name>` / `AGENT_<NAME>` binding). */
29
46
  name: string;
47
+ /** Override the model-facing tool name (default `agent_<name>`). */
30
48
  toolName?: string;
31
49
  }
50
+ /** The generic status/poll tool advertised alongside the per-agent tools. */
32
51
  declare const AGENT_STATUS_TOOL_NAME = "lunora_agent_status";
52
+ /**
53
+ * The uniform input schema every agent tool advertises. Agents share ONE run
54
+ * input (`@lunora/agent` has no per-agent validator), so there is nothing to
55
+ * derive per agent — a single static schema is reused for every agent tool.
56
+ */
33
57
  declare const AGENT_RUN_INPUT_SCHEMA: ToolInputSchema;
58
+ /**
59
+ * Parse `LUNORA_MCP_AGENTS` — a `;`-separated list of `name:description` pairs,
60
+ * e.g. `"support:Handles support questions;billing:Billing help"`. The
61
+ * description may itself contain colons (only the FIRST colon splits). Blank
62
+ * entries and entries with an empty name/description are skipped.
63
+ */
34
64
  declare const parseAgentsEnv: (raw: string | undefined) => McpAgentExposure[];
65
+ /**
66
+ * The tools this module advertises. Fail-closed: only the boolean `true` opts
67
+ * in (an env-plumbed caller could pass a truthy string), and the tools appear
68
+ * ONLY when at least one agent is exposed — so an agent-free or non-opted-in
69
+ * server never lists them.
70
+ */
35
71
  declare const agentToolDefinitions: (exposures: ReadonlyArray<McpAgentExposure>, allowAgents: boolean) => ReadonlyArray<ToolDefinition>;
72
+ /** Options threaded into a single agent tool dispatch. */
36
73
  interface CallAgentToolOptions {
74
+ /** Opt-in gate — must be exactly `true` or the call is refused fail-closed. */
37
75
  allowAgents: boolean;
76
+ /** The exposures advertised by this server. */
38
77
  exposures: ReadonlyArray<McpAgentExposure>;
78
+ /** Wall-clock budget a single call awaits before returning a pending result. */
39
79
  maxWaitMs?: number;
80
+ /** Delay between thread-status polls. */
40
81
  pollIntervalMs?: number;
82
+ /** Test seam replacing the between-poll wait; production uses a real timer. */
41
83
  wait?: (ms: number) => Promise<void>;
42
84
  }
85
+ /**
86
+ * Dispatch an agent tool call: start a durable run via `agents:agentRun`, then
87
+ * await-with-timeout — poll `agents:agentThread` until terminal (returning the
88
+ * final answer from `agents:agentMessages`) or, on budget exhaustion, return a
89
+ * NON-error pending payload the caller resumes with `lunora_agent_status`.
90
+ *
91
+ * Fail-closed: refused at dispatch unless `allowAgents === true`, mirroring the
92
+ * `allowWrites` guard — starting a run is a side effect and must not ride the
93
+ * read-only default.
94
+ */
43
95
  declare const callAgentTool: (client: LunoraClient, name: string, input: Record<string, unknown>, options: CallAgentToolOptions) => Promise<ToolResult>;
44
96
  interface LunoraMcpServerOptions {
97
+ /** Wall-clock budget a single agent tool call awaits before returning a pending result. */
45
98
  agentMaxWaitMs?: number;
99
+ /** Delay between agent thread-status polls. */
46
100
  agentPollIntervalMs?: number;
101
+ /** The agents this server fronts as MCP tools (see `allowAgents`). */
47
102
  agents?: ReadonlyArray<McpAgentExposure>;
103
+ /**
104
+ * Expose the per-agent tools (`agent_<name>` + the generic
105
+ * `lunora_agent_status`). Defaults to `false`, mirroring `allowWrites`:
106
+ * starting a durable agent run is a side effect, so the agent tools are
107
+ * omitted from the advertised list AND refused at dispatch unless explicitly
108
+ * opted in. Only takes effect together with a non-empty `agents` list.
109
+ */
48
110
  allowAgents?: boolean;
111
+ /**
112
+ * Expose `lunora_find_related`, which returns raw table rows read through the
113
+ * admin writer, so RLS policies and column masks do not apply. Defaults to
114
+ * `false`, for the same reason as `allowObservability`. Only takes effect
115
+ * when a `token` resolved. On the OAuth-protected path the verified token must
116
+ * also carry the data-read scope (see `DATA_READ_SCOPE` in `./tools`).
117
+ */
118
+ allowDataReads?: boolean;
119
+ /**
120
+ * Expose the observability tools (`lunora_get_logs`, `lunora_get_issues`,
121
+ * `lunora_get_advisories`, `lunora_get_query_insights`,
122
+ * `lunora_get_migration_status`). Defaults to `false`, mirroring
123
+ * `allowWrites`: they are read-only, but every row they return — log lines,
124
+ * request metadata, grouped error messages — is production user data that
125
+ * lands in the model's context and therefore at its provider. Holding the
126
+ * admin bearer is not consent to ship that, so it is a separate opt-in;
127
+ * without it the tools are omitted from the advertised list AND refused at
128
+ * dispatch. Only takes effect when a `token` resolved. On the OAuth-protected
129
+ * path the verified token must also carry the observability scope (see
130
+ * `OBSERVABILITY_SCOPE` in `./tools`); this option stays the outer gate.
131
+ */
132
+ allowObservability?: boolean;
133
+ /**
134
+ * Expose the write tools (`lunora_run_mutation` / `lunora_run_action`).
135
+ * Defaults to `false`: the server is READ-ONLY unless explicitly opted in,
136
+ * so a prompt-injected or misaligned agent can't mutate the deployment with
137
+ * the configured token. When false the write tools are omitted from the
138
+ * advertised tool list AND refused at dispatch.
139
+ */
49
140
  allowWrites?: boolean;
141
+ /**
142
+ * Pre-built client (test injection). When omitted a `LunoraClient` is
143
+ * created from `url`/`token`/`fetch`.
144
+ */
50
145
  client?: LunoraClient;
146
+ /** `fetch` implementation; defaults to the ambient global. */
51
147
  fetch?: typeof fetch;
148
+ /**
149
+ * Bearer token sent on every RPC. **Required** alongside `url`, and it must
150
+ * be the deployment's **admin bearer**: the introspection/allowlist path
151
+ * every tool depends on (`lunora_list_functions`, `lunora_list_tables`, and
152
+ * the `assertRunnable` precheck that runs before every `run` tool) hits
153
+ * admin-gated `/_lunora/admin/*` routes, so no scoped/app token works
154
+ * today — it would 403 (`ADMIN_FORBIDDEN`) on the first tool call. The
155
+ * read-only guarantee is therefore NOT enforced by the token's scope; it is
156
+ * enforced in-process via `allowWrites: false` (the default), which omits
157
+ * the write tools from the advertised list and refuses them at dispatch.
158
+ *
159
+ * Because EVERY tool needs it, omitting it is a misconfiguration rather than
160
+ * a reduced-capability mode, and `createLunoraMcpServer` says so at
161
+ * construction instead of advertising a surface that 403s on first use. The
162
+ * one exception is the `client` injection seam (tests / a pre-authenticated
163
+ * client), where this server cannot know what the client can reach and so
164
+ * reads "unknown" fail-closed: the privileged observability tools stay
165
+ * unadvertised and are refused at dispatch.
166
+ */
52
167
  token?: string;
168
+ /** Base URL of the deployed Lunora Worker. Required unless `client` is given. */
53
169
  url?: string;
54
170
  }
171
+ /**
172
+ * Build an MCP `Server` whose tools talk to a Lunora deployment. The server is
173
+ * transport-agnostic — call `.connect(transport)` yourself, or use
174
+ * `connectStdio` for the common stdio case.
175
+ *
176
+ * Tool calls are dispatched through `callTool`, which the deployment reaches
177
+ * over HTTP RPC. No WebSocket is opened (the tools never subscribe), so this is
178
+ * safe to run as a short-lived stdio process.
179
+ */
55
180
  declare const createLunoraMcpServer: (options: LunoraMcpServerOptions) => Server;
181
+ /**
182
+ * Build the server and connect it over stdio — the transport MCP clients use
183
+ * when they spawn the `lunora-mcp` binary. Resolves once the transport is
184
+ * connected; the process then stays alive serving requests.
185
+ */
56
186
  declare const connectStdio: (options: LunoraMcpServerOptions) => Promise<Server>;
57
- type McpFetchHandler = (request: Request) => Promise<Response>;
58
- declare const createMcpFetchHandler: (options: LunoraMcpServerOptions) => McpFetchHandler;
187
+ /**
188
+ * The verified access-token payload better-auth hands a protected handler.
189
+ *
190
+ * A JWT payload is an open bag of claims, so this is deliberately an index
191
+ * signature with the two entries this module reads named. It is structurally
192
+ * satisfied by `jose`'s `JWTPayload`, which is what better-auth passes.
193
+ */
194
+ interface McpAccessTokenClaims {
195
+ readonly [claim: string]: unknown;
196
+ /** Space-delimited granted scopes (RFC 6749 §3.3). */
197
+ readonly scope?: unknown;
198
+ /** Subject — the user the token was issued for. */
199
+ readonly sub?: string;
200
+ }
201
+ /**
202
+ * The MCP auth gate: wraps a claims-aware handler into a plain fetch handler.
203
+ *
204
+ * Declared structurally here rather than imported from `@better-auth/mcp`,
205
+ * following the same rule `./paid` follows for `@lunora/x402`: a type import
206
+ * from a package this one does not depend on puts that package's `.d.ts` into
207
+ * the build graph, and a consumer that never installs it never builds it
208
+ * either — so the dts bundler looks for a `dist/` that does not exist and fails
209
+ * the build. Structural typing costs nothing here because this module never
210
+ * inspects the gate; it only applies it.
211
+ *
212
+ * Both better-auth entry points partially apply to this shape:
213
+ * `(handler) => requireMcpAuth(auth, handler, opts)` and
214
+ * `(handler) => createMcpProtectedRequestHandler(options, handler)`.
215
+ */
216
+ type McpAuthProtect = (handler: (request: Request, claims: McpAccessTokenClaims) => Promise<Response>) => McpFetchHandler;
217
+ /** Server options, or a function deriving them from the request's verified claims. */
218
+ type AuthedMcpServerOptions = ((claims: McpAccessTokenClaims) => LunoraMcpServerOptions | Promise<LunoraMcpServerOptions>) | LunoraMcpServerOptions;
219
+ interface AuthedMcpFetchHandlerOptions {
220
+ /**
221
+ * Largest accepted request body, in bytes — enforced while the body streams
222
+ * in, not after it is buffered. Defaults to `DEFAULT_MAX_REQUEST_BYTES`
223
+ * (128 KiB), which a value that is not a non-negative safe integer also
224
+ * falls back to.
225
+ */
226
+ maxRequestBytes?: number;
227
+ /**
228
+ * The OAuth gate to mount the MCP server behind. Pass
229
+ * `(handler) => requireMcpAuth(auth, handler, opts)` from
230
+ * `@lunora/auth/plugins`.
231
+ */
232
+ protect: McpAuthProtect;
233
+ /**
234
+ * The Lunora MCP server to serve once a request is authorized — either a
235
+ * fixed options object, or a function of the verified token claims so tool
236
+ * exposure can follow the scopes the token actually carries.
237
+ */
238
+ server: AuthedMcpServerOptions;
239
+ /**
240
+ * Step-up for the side-effecting tools: the write tools
241
+ * (`lunora_run_mutation` / `lunora_run_action`) and the agent tools (each
242
+ * `agent_<name>` and `lunora_agent_status`, since starting a durable run is a
243
+ * side effect). A token without `scope` still sees them in `tools/list`, and
244
+ * a `tools/call` to one throws `challenge([scope])` instead of running, so the
245
+ * client can re-authorize for the scope and retry. Unset, tools follow
246
+ * `allowWrites` / `allowAgents` alone. The raw-row and observability families
247
+ * need their own token scopes with or without `stepUp`; without it a call
248
+ * without the scope is refused as a tool error, not challenged.
249
+ */
250
+ stepUp?: {
251
+ /**
252
+ * Build the error that makes the gate answer 403 `insufficient_scope`
253
+ * naming `scopes`. Pass `createInsufficientScopeError` from
254
+ * `@lunora/auth/plugins`: better-auth only turns an error that factory
255
+ * created into the challenge.
256
+ */
257
+ challenge: (scopes: string[]) => unknown;
258
+ /** The scope a call to a side-effecting tool needs, e.g. `"lunora:write"`. */
259
+ scope: string;
260
+ };
261
+ }
262
+ /**
263
+ * Parse an access token's `scope` claim into a set.
264
+ *
265
+ * RFC 6749 §3.3 makes `scope` a space-delimited string, and better-auth issues
266
+ * it that way; anything else (absent, or a non-string an extension wrote)
267
+ * yields an empty set rather than throwing, so a scope check on a malformed
268
+ * token denies instead of crashing the tool call.
269
+ */
270
+ declare const mcpTokenScopes: (claims: McpAccessTokenClaims) => ReadonlySet<string>;
271
+ /**
272
+ * Build an OAuth-protected stateless Streamable-HTTP fetch handler for a Lunora
273
+ * MCP server.
274
+ *
275
+ * Unauthenticated requests never reach the MCP server at all: `protect` answers
276
+ * them with the RFC 9728 `WWW-Authenticate` challenge that starts the client's
277
+ * authorization flow. An authorized request builds a fresh proxy server from
278
+ * `server` (resolved against the verified claims) and serves it through
279
+ * {@link serveStateless}, exactly as the unprotected `createMcpFetchHandler`
280
+ * does — the transport behaviour is identical, only the gate is new.
281
+ *
282
+ * A fixed `server` object names one deployment, so its `LunoraClient` is
283
+ * resolved once and shared: the public-function registry memo in `./tools` is
284
+ * keyed by client identity and never hits when each request builds its own. The
285
+ * `(claims) => …` form is per-request by construction — the claims decide which
286
+ * deployment and token to use — so it keeps a client per request.
287
+ */
288
+ declare const createAuthedMcpFetchHandler: (options: AuthedMcpFetchHandlerOptions) => McpFetchHandler;
289
+ /** {@link createMcpFetchHandler} options: the server's, plus this transport's body limit. */
290
+ interface McpFetchHandlerOptions extends LunoraMcpServerOptions {
291
+ /**
292
+ * Largest accepted request body, in bytes — enforced while the body streams
293
+ * in, not after it is buffered. Defaults to `DEFAULT_MAX_REQUEST_BYTES`
294
+ * (128 KiB), which a value that is not a non-negative safe integer also
295
+ * falls back to.
296
+ */
297
+ maxRequestBytes?: number;
298
+ }
299
+ /**
300
+ * Build a stateless Streamable-HTTP fetch handler for a Lunora MCP server. Each
301
+ * invocation constructs a fresh proxy server and serves the request through
302
+ * {@link serveStateless}.
303
+ *
304
+ * The `LunoraClient` is resolved ONCE, here, and shared by every request: it is
305
+ * the same deployment on each one, and the public-function registry memo in
306
+ * `./tools` is keyed by client identity, so a per-request client would re-fetch
307
+ * that registry on every tool call. A misconfiguration (`url` without `token`)
308
+ * therefore throws when the handler is built rather than on first request,
309
+ * which is where `createLunoraMcpServer` already documents reporting it.
310
+ */
311
+ declare const createMcpFetchHandler: (options: McpFetchHandlerOptions) => McpFetchHandler;
312
+ /** A Lunora deployment the tools dispatch against. */
313
+ interface LocalDeployment {
314
+ token?: string;
315
+ url: string;
316
+ }
317
+ /**
318
+ * Where the deployment comes from: a fixed value, or a function consulted on
319
+ * every tool call.
320
+ *
321
+ * The resolver form exists because an editor spawns this server when the
322
+ * project opens — routinely *before* `lunora dev` is running, and it keeps the
323
+ * process alive across every restart afterwards. A URL captured once at startup
324
+ * would therefore be absent for the entire first session and stale after the
325
+ * first restart.
326
+ */
327
+ type LocalDeploymentSource = (() => LocalDeployment | undefined) | LocalDeployment;
328
+ interface LocalMcpServerOptions {
329
+ /**
330
+ * Expose the deployment write tools (`lunora_run_mutation` /
331
+ * `lunora_run_action`). Defaults to `false` — the same fail-closed default
332
+ * as the remote server. Locally the blast radius is dev data rather than
333
+ * production, but a mutation is still a side effect an agent should be
334
+ * granted deliberately.
335
+ */
336
+ allowWrites?: boolean;
337
+ /**
338
+ * The Lunora deployment (usually the running dev server) to expose. Omit to
339
+ * leave the deployment tools out entirely.
340
+ */
341
+ deployment?: LocalDeploymentSource;
342
+ /** Docs site origin backing the documentation tools; `false` omits them. */
343
+ docs?: false | {
344
+ baseUrl?: string;
345
+ };
346
+ /** Extra tools to compose in, e.g. the CLI's local dev-server tools. */
347
+ extraTools?: ReadonlyArray<McpTool>;
348
+ /** `fetch` implementation; defaults to the ambient global. */
349
+ fetch?: typeof fetch;
350
+ /** Version reported in the MCP handshake — the host CLI's, not this package's. */
351
+ version?: string;
352
+ }
353
+ /** Server identity advertised in the MCP `initialize` handshake. */
354
+ declare const LOCAL_SERVER_NAME = "lunora";
355
+ /** Shown when a deployment tool is called and no dev server can be found. */
356
+ 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).";
357
+ /**
358
+ * Assemble the tool list, in the order it is advertised: docs first (the
359
+ * surface that always works), then the caller's extras, then the error catalog
360
+ * (compiled in, so it needs no deployment either), then the deployment tools.
361
+ * Order also decides precedence — `createToolServer` keeps the first
362
+ * registration of a duplicated name.
363
+ *
364
+ * `clientFor` is the shared client cache built once by
365
+ * {@link createLocalMcpServer} and threaded into both the tool and resource
366
+ * surfaces. Exported (and called directly by tests) without going through
367
+ * `createLocalMcpServer`, so a caller that omits it gets a private,
368
+ * call-scoped cache — same shape as before this surface was shared, just
369
+ * without the cross-surface sharing that only matters once a resource
370
+ * surface exists alongside it.
371
+ */
372
+ declare const localTools: (options: LocalMcpServerOptions, clientFor?: (deployment: LocalDeployment) => LunoraClient) => ReadonlyArray<McpTool>;
373
+ /** Build the composed local server without connecting a transport. */
374
+ declare const createLocalMcpServer: (options?: LocalMcpServerOptions) => Server;
375
+ /**
376
+ * Build the composed local server and connect it over stdio — the transport an
377
+ * MCP client uses when it spawns `lunora mcp serve`. Resolves once connected;
378
+ * the process then stays alive serving requests.
379
+ */
380
+ declare const connectLocalStdio: (options?: LocalMcpServerOptions) => Promise<Server>;
381
+ /** A tool handler: receives the call's `arguments` bag, returns an MCP tool result. */
382
+ /**
383
+ * The x402 vocabulary this module needs, declared here rather than imported.
384
+ *
385
+ * The x402 package is an optional peer, and a type import from its `charge`
386
+ * entry puts its `.d.ts` back into this package's build graph:
387
+ * a consumer that never installs x402 never builds it either, so the dts bundler
388
+ * looks for a `dist/` that does not exist and fails. That is not hypothetical —
389
+ * it broke the docs site build, which runs a filtered build over the docs app and its dependency closure
390
+ * and therefore never builds x402.
391
+ *
392
+ * Declaring them locally is safe because this module never *inspects* a charge
393
+ * config; it forwards it whole to `createChargeMiddleware`. The index signature
394
+ * keeps a real charge config assignable as x402 grows fields.
395
+ */
396
+ /** Mirrors x402's `X402Price` — a decimal string like `"$0.05"`, or a number. */
397
+ type X402Price = number | string;
398
+ /** Mirrors x402's charge config with the per-tool price omitted. */
399
+ interface X402ChargeSettings {
400
+ /** Network this resource settles on. */
401
+ readonly network: string;
402
+ /** Everything else x402 accepts, forwarded untouched. */
403
+ readonly [key: string]: unknown;
404
+ /** Payout wallet(s), per network family. */
405
+ readonly recipient: {
406
+ readonly evm?: string;
407
+ readonly svm?: string;
408
+ };
409
+ }
59
410
  type ToolHandler = (arguments_: Record<string, unknown>) => Promise<ToolResult> | ToolResult;
411
+ /** Registration shape for a free tool. */
60
412
  interface RegisterToolOptions {
413
+ /** Optional MCP tool annotations (`readOnlyHint`, `title`, …). */
61
414
  annotations?: Tool["annotations"];
415
+ /** Human/model-facing description of what the tool does. */
62
416
  description: string;
417
+ /** JSON-Schema object describing the tool's arguments. */
63
418
  inputSchema: ToolInputSchema;
419
+ /** Unique tool name (the MCP `tools/call` `name`). */
64
420
  name: string;
65
421
  }
422
+ /** Registration shape for a paid tool: a {@link RegisterToolOptions} plus its USD price. */
66
423
  interface RegisterPaidToolOptions extends RegisterToolOptions {
424
+ /** USD price per call (e.g. `"$0.05"`), charged via x402 before dispatch. */
67
425
  price: X402Price;
68
426
  }
69
- type PaidMcpChargeConfig = Omit<X402ChargeConfig, "price">;
427
+ /** x402 settlement vocabulary shared by every paid tool (network, recipient, facilitator); price is per-tool. */
428
+ type PaidMcpChargeConfig = X402ChargeSettings;
429
+ /** Config for `createPaidMcpServer`. */
70
430
  interface PaidMcpServerConfig {
431
+ /** The worker-level x402 charge config; each paid tool supplies only its own `price`. */
71
432
  charge: PaidMcpChargeConfig;
433
+ /**
434
+ * Largest accepted request body, in bytes — enforced while the body streams
435
+ * in, not after it is buffered. Defaults to `DEFAULT_MAX_REQUEST_BYTES`
436
+ * (128 KiB), which a value that is not a non-negative safe integer also
437
+ * falls back to.
438
+ */
439
+ maxRequestBytes?: number;
440
+ /** Name/version advertised in the MCP `initialize` handshake. Defaults to `lunora-paid-mcp`. */
72
441
  serverInfo?: {
73
442
  name: string;
74
443
  version: string;
75
444
  };
76
445
  }
446
+ /**
447
+ * The Worker execution context, as this module reads it: only `waitUntil`, and
448
+ * structurally, so the package takes no `@cloudflare/workers-types` dependency.
449
+ */
450
+ interface PaidMcpExecutionContext {
451
+ waitUntil?: (promise: Promise<unknown>) => void;
452
+ }
453
+ /**
454
+ * The paid server's fetch handler.
455
+ *
456
+ * Unlike the free `McpFetchHandler` it takes the Worker's full
457
+ * `(request, env, ctx)` triple — the shape `export default { fetch }` is called
458
+ * with — because the x402 receipt sink NEEDS `ctx.waitUntil`: work that is
459
+ * neither awaited into the response nor registered with it is cancelled when the
460
+ * request ends, so an async `onReceipt` (inserting the settled payment into a
461
+ * durable table) frequently never runs while the money has already moved
462
+ * on-chain. `env` is accepted and ignored so the handler drops straight into the
463
+ * default export; both are optional, so a non-Workers caller may still invoke it
464
+ * with a bare `Request` (the middleware then simply sees no `waitUntil`).
465
+ */
466
+ type PaidMcpFetchHandler = (request: Request, env?: unknown, context?: PaidMcpExecutionContext) => Promise<Response>;
467
+ /** A paid MCP server: register free/paid tools, then serve over Streamable HTTP. */
77
468
  interface PaidMcpServer {
78
- readonly fetchHandler: McpFetchHandler;
469
+ /** The Streamable-HTTP fetch handler; gates each paid `tools/call` behind x402. */
470
+ readonly fetchHandler: PaidMcpFetchHandler;
471
+ /** Register a **paid** tool: its dispatch runs the x402 charge middleware first. */
79
472
  paidTool: (options: RegisterPaidToolOptions, handler: ToolHandler) => void;
473
+ /** Register a **free** tool (coexists with paid tools on the same server). */
80
474
  tool: (options: RegisterToolOptions, handler: ToolHandler) => void;
81
475
  }
476
+ /**
477
+ * Create a paid MCP server. Register free tools with `tool()` and priced tools
478
+ * with `paidTool()` (they coexist), then serve `fetchHandler` over HTTP.
479
+ *
480
+ * The server is **stateless**: `fetchHandler` builds a fresh `Server` per
481
+ * request (reading the live tool registry), so tools registered before the
482
+ * first request are all visible. Each priced tool memoises one initialised
483
+ * `ChargeMiddleware` (keyed by tool name, baking that tool's price and naming
484
+ * the tool as the challenge `resource`); a failed init is not cached, so a
485
+ * transient facilitator outage retries on the next call.
486
+ */
82
487
  declare const createPaidMcpServer: (config: PaidMcpServerConfig) => PaidMcpServer;
83
- 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 };
488
+ export { AGENT_RUN_INPUT_SCHEMA, AGENT_STATUS_TOOL_NAME, type AuthedMcpFetchHandlerOptions, type AuthedMcpServerOptions,
489
+ /**
490
+ * `@lunora/mcp` — Model Context Protocol servers for Lunora. This entry exposes
491
+ * a *deployment* to AI agents; the `@lunora/mcp/docs` subpath exposes the
492
+ * framework's *documentation* (credential-free, and safe to host publicly).
493
+ *
494
+ * The deployment server: It registers tools for introspecting a deployment
495
+ * (`lunora_list_functions`, `lunora_list_tables`) and invoking its functions
496
+ * (`lunora_run_query`, plus `lunora_run_mutation` and `lunora_run_action` when
497
+ * writes are enabled), each backed by `LunoraClient` over HTTP RPC, plus
498
+ * `lunora_explain_error` — a credential-free read of the static error catalog
499
+ * (status, title, hint, matched solution) that needs no deployment at all. It also
500
+ * exposes the deployment's observability reads (`lunora_get_logs`,
501
+ * `lunora_get_issues`, `lunora_get_advisories`, `lunora_get_query_insights`,
502
+ * `lunora_get_migration_status`) when `allowObservability` (or the
503
+ * LUNORA_MCP_ALLOW_OBSERVABILITY env) is set — read-only, but they return
504
+ * production user data, so they are omitted entirely without it. The server is
505
+ * read-only by default — the write tools are exposed only when `allowWrites`
506
+ * (or the `LUNORA_MCP_ALLOW_WRITES` env) is set, and every run tool is
507
+ * allowlisted against the deployment's discovered public functions. Past that
508
+ * gate the two write tools run a two-step confirmation handshake: the first
509
+ * call writes nothing and returns the proposed action plus a self-verifying
510
+ * `actionDigest`, and only a second call carrying `confirmed: true` and that
511
+ * digest executes (see `./write-confirmation`). It can also
512
+ * front durable `@lunora/agent` runs as `agent_<name>` tools when `allowAgents`
513
+ * (or `LUNORA_MCP_ALLOW_AGENTS` + `LUNORA_MCP_AGENTS`) is set. Run the
514
+ * `lunora-mcp` binary (configured via the `LUNORA_URL`, `LUNORA_ADMIN_TOKEN`,
515
+ * and `LUNORA_MCP_ALLOW_WRITES` env vars) for the stdio transport, serve the
516
+ * server remotely over Streamable HTTP with `createMcpFetchHandler` (a
517
+ * Workers-ready `Request` → `Response` handler), or build a server
518
+ * programmatically with `createLunoraMcpServer` and connect any transport.
519
+ *
520
+ * A remote endpoint is reachable by anyone who knows its URL, and the tools
521
+ * carry the deployment's admin bearer — so for a public deployment use
522
+ * `createAuthedMcpFetchHandler` instead, which mounts the same server behind
523
+ * better-auth's MCP OAuth gate (`requireMcpAuth` from `@lunora/auth/plugins`)
524
+ * and can scope tool exposure to the access token's own scopes.
525
+ */
526
+ type CallAgentToolOptions, LOCAL_SERVER_NAME, type LocalDeployment, type LocalDeploymentSource, type LocalMcpServerOptions, type LunoraMcpServerOptions, type McpAccessTokenClaims,
527
+ /**
528
+ * `@lunora/mcp` — Model Context Protocol servers for Lunora. This entry exposes
529
+ * a *deployment* to AI agents; the `@lunora/mcp/docs` subpath exposes the
530
+ * framework's *documentation* (credential-free, and safe to host publicly).
531
+ *
532
+ * The deployment server: It registers tools for introspecting a deployment
533
+ * (`lunora_list_functions`, `lunora_list_tables`) and invoking its functions
534
+ * (`lunora_run_query`, plus `lunora_run_mutation` and `lunora_run_action` when
535
+ * writes are enabled), each backed by `LunoraClient` over HTTP RPC, plus
536
+ * `lunora_explain_error` — a credential-free read of the static error catalog
537
+ * (status, title, hint, matched solution) that needs no deployment at all. It also
538
+ * exposes the deployment's observability reads (`lunora_get_logs`,
539
+ * `lunora_get_issues`, `lunora_get_advisories`, `lunora_get_query_insights`,
540
+ * `lunora_get_migration_status`) when `allowObservability` (or the
541
+ * LUNORA_MCP_ALLOW_OBSERVABILITY env) is set — read-only, but they return
542
+ * production user data, so they are omitted entirely without it. The server is
543
+ * read-only by default — the write tools are exposed only when `allowWrites`
544
+ * (or the `LUNORA_MCP_ALLOW_WRITES` env) is set, and every run tool is
545
+ * allowlisted against the deployment's discovered public functions. Past that
546
+ * gate the two write tools run a two-step confirmation handshake: the first
547
+ * call writes nothing and returns the proposed action plus a self-verifying
548
+ * `actionDigest`, and only a second call carrying `confirmed: true` and that
549
+ * digest executes (see `./write-confirmation`). It can also
550
+ * front durable `@lunora/agent` runs as `agent_<name>` tools when `allowAgents`
551
+ * (or `LUNORA_MCP_ALLOW_AGENTS` + `LUNORA_MCP_AGENTS`) is set. Run the
552
+ * `lunora-mcp` binary (configured via the `LUNORA_URL`, `LUNORA_ADMIN_TOKEN`,
553
+ * and `LUNORA_MCP_ALLOW_WRITES` env vars) for the stdio transport, serve the
554
+ * server remotely over Streamable HTTP with `createMcpFetchHandler` (a
555
+ * Workers-ready `Request` → `Response` handler), or build a server
556
+ * programmatically with `createLunoraMcpServer` and connect any transport.
557
+ *
558
+ * A remote endpoint is reachable by anyone who knows its URL, and the tools
559
+ * carry the deployment's admin bearer — so for a public deployment use
560
+ * `createAuthedMcpFetchHandler` instead, which mounts the same server behind
561
+ * better-auth's MCP OAuth gate (`requireMcpAuth` from `@lunora/auth/plugins`)
562
+ * and can scope tool exposure to the access token's own scopes.
563
+ */
564
+ type McpAgentExposure, type McpAuthProtect, type McpFetchHandler, type McpFetchHandlerOptions, type McpTool, NO_DEPLOYMENT_MESSAGE, OBSERVABILITY_TOOL_DEFINITIONS, type PaidMcpChargeConfig, type PaidMcpExecutionContext, type PaidMcpFetchHandler, type PaidMcpServer, type PaidMcpServerConfig, READ_ONLY_TOOL_DEFINITIONS, type RegisterPaidToolOptions, type RegisterToolOptions, type ToolDefinition, type ToolHandler, type ToolInputSchema, type ToolResult, WRITE_TOOL_DEFINITIONS, agentToolDefinitions, callAgentTool, callTool, connectLocalStdio, connectStdio, createAuthedMcpFetchHandler, createLocalMcpServer, createLunoraMcpServer, createMcpFetchHandler, createPaidMcpServer, localTools, mcpTokenScopes, parseAgentsEnv, toolDefinitions };