akanjs 3.2.0-rc.30 → 3.2.0-rc.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ARCHITECTURE.md +2 -0
- package/CHANGELOG.md +21 -0
- package/client/route/PageDefinition.ts +11 -3
- package/client/route/routeArgs.ts +1 -0
- package/fetch/requestStorage.ts +1 -0
- package/package.json +1 -1
- package/server/index.ts +22 -0
- package/server/mcp/McpApps.ts +32 -2
- package/server/mcp/McpPages.ts +34 -12
- package/server/mcp/McpRouter.ts +3 -1
- package/server/remote/RemoteFetch.ts +161 -0
- package/server/remote/RemoteMcp.ts +242 -0
- package/server/remote/RemoteOAuth.ts +270 -0
- package/server/remote/RemoteSource.ts +214 -0
- package/server/remote/index.ts +17 -0
- package/server/remote/remoteError.ts +19 -0
- package/server/routeTreeBuilder.ts +3 -1
- package/server/rscFlightStream.ts +2 -0
- package/server/rscPagePrompts.ts +54 -9
- package/server/rscStaticApp.tsx +73 -0
- package/server/rscWorker.tsx +32 -0
- package/server/rscWorkerHost.ts +32 -0
- package/server/ssrStaticApp.tsx +243 -0
- package/server/webRouter.ts +3 -0
- package/server/webStaticApp.ts +62 -0
- package/service/agentLoop/agentLoop.ts +53 -9
- package/service/agentLoop/agentLoopTypes.ts +54 -7
- package/service/agentLoop/loopRemotes.ts +165 -0
- package/service/agentLoop/loopRequest.ts +26 -1
- package/service/agentLoop/loopToolkits.ts +44 -9
- package/signal/index.ts +3 -0
- package/signal/mcp/mcpProtocol.ts +6 -1
- package/signal/mcp/pagePrompt.ts +15 -0
- package/types/client/route/PageDefinition.d.ts +5 -2
- package/types/client/route/routeArgs.d.ts +1 -0
- package/types/fetch/requestStorage.d.ts +1 -0
- package/types/server/index.d.ts +1 -0
- package/types/server/logging/rotatingLogWriter.d.ts +1 -1
- package/types/server/mcp/McpApps.d.ts +6 -2
- package/types/server/mcp/McpPages.d.ts +2 -1
- package/types/server/remote/RemoteFetch.d.ts +42 -0
- package/types/server/remote/RemoteMcp.d.ts +52 -0
- package/types/server/remote/RemoteOAuth.d.ts +58 -0
- package/types/server/remote/RemoteSource.d.ts +51 -0
- package/types/server/remote/index.d.ts +5 -0
- package/types/server/remote/remoteError.d.ts +12 -0
- package/types/server/remote.d.ts +1 -0
- package/types/server/rscFlightStream.d.ts +1 -0
- package/types/server/rscPagePrompts.d.ts +13 -0
- package/types/server/rscStaticApp.d.ts +28 -0
- package/types/server/rscWorkerHost.d.ts +3 -0
- package/types/server/ssrStaticApp.d.ts +20 -0
- package/types/server/webStaticApp.d.ts +8 -0
- package/types/service/agentLoop/agentLoop.d.ts +1 -0
- package/types/service/agentLoop/agentLoopTypes.d.ts +51 -4
- package/types/service/agentLoop/loopRemotes.d.ts +36 -0
- package/types/service/agentLoop/loopRequest.d.ts +1 -1
- package/types/service/agentLoop/loopToolkits.d.ts +5 -2
- package/types/signal/index.d.ts +1 -1
- package/types/signal/mcp/mcpProtocol.d.ts +5 -0
- package/types/signal/mcp/pagePrompt.d.ts +13 -0
- package/types/webkit/McpAppHost.d.ts +24 -0
- package/types/webkit/index.d.ts +3 -0
- package/types/webkit/needsBrowser.d.ts +5 -0
- package/webkit/McpAppHost.ts +122 -0
- package/webkit/index.ts +3 -0
- package/webkit/lazy.tsx +5 -1
- package/webkit/needsBrowser.ts +10 -0
package/ARCHITECTURE.md
CHANGED
|
@@ -149,6 +149,7 @@ Declared in [server/rscWorker.tsx](server/rscWorker.tsx).
|
|
|
149
149
|
| `log-level` | `RscWorker` | `RscRenderer` |
|
|
150
150
|
| `page-prompts` | `RscWorker` | `RscRenderer` |
|
|
151
151
|
| `page-prompt.run` | `RscWorker` | `RscRenderer` |
|
|
152
|
+
| `page-prompt.draw` | `RscWorker` | `RscRenderer` |
|
|
152
153
|
| `page-prompts.visible` | `RscWorker` | `RscRenderer` |
|
|
153
154
|
| `web-manifest` | `RscWorker` | `RscRenderer` |
|
|
154
155
|
|
|
@@ -174,6 +175,7 @@ Declared in [server/rscWorkerHost.ts](server/rscWorkerHost.ts).
|
|
|
174
175
|
| `log.records` | `LogForwarder` | `RscWorker` |
|
|
175
176
|
| `page-prompts.result` | `RscRenderer` | `RscWorker` |
|
|
176
177
|
| `page-prompt.result` | `RscRenderer` | `RscWorker` |
|
|
178
|
+
| `page-prompt.draw.result` | `RscRenderer` | `RscWorker` |
|
|
177
179
|
| `page-prompts.visible.result` | `RscRenderer` | `RscWorker` |
|
|
178
180
|
| `web-manifest.result` | `RscRenderer` | `RscWorker` |
|
|
179
181
|
| `error` | `RscRenderFallbacks`, `RscRenderer` | `RscWorker` |
|
package/CHANGELOG.md
CHANGED
|
@@ -56,6 +56,18 @@
|
|
|
56
56
|
|
|
57
57
|
A run without `compact` ends on the refusal as before. With `compact` set, a refused round now costs up to two more model calls (the summary and the retry) before the run ends. `AgentTurnStream.failure(...).overflow` and `RunnerEvent`'s error `overflow` gain an optional `requested`; code reading only `limit` needs no change.
|
|
58
58
|
|
|
59
|
+
- fd76e6f: `agentService.loop` can call other MCP servers as the run's account, each one a toolkit the model opens.
|
|
60
|
+
|
|
61
|
+
- `remotes: AgentLoopRemote[]` on the loop request. A remote is listed in `openToolkit` by its `name` and `description` and is not contacted until the model opens it; its tools then read `<name>.<tool>`. Opening one the account has no connection to ends the run `awaiting` with `connect: "<name>"`, and a resume with the stored messages opens it once connected.
|
|
62
|
+
- Opening a remote taints the run: its tool names, descriptions and schemas, or the error of a failed open, are another party's text. A request that passes `remotes` with no `approve` is refused before any model call, as `base.error.requiredArgument` naming `approve`: a call's arguments leave for that server, whatever the remote calls its tool. `approve` receives the target as `state.remote`, and a tool the remote does not call read-only as `needsConfirm`. One remote's listing stops at 120,000 characters, the rest counted in the open's `omitted`.
|
|
63
|
+
- A `toolResult` event carries `view` when the remote tool is a `page().app()`: where its screen is, for the page to draw. Only `href`, `static` and `resourceUri` are taken from what the remote sent. A view with none of them is not sent. It reaches neither the model nor `onMessage`.
|
|
64
|
+
- `akanjs/server` exports the client half of `/mcp` and `/oauth`: `RemoteFetch` (https only, no private address, no redirect, the checked address pinned), `RemoteOAuth` (discovery, registration, PKCE, exchange, refresh, revoke), `RemoteMcp` (Streamable HTTP, request and answer) and `RemoteSource`, which implements `AgentLoopRemote` over them. A failure is a `RemoteError` with one of six `remote…` codes. Discovery refuses OAuth metadata that names a different issuer, or a resource outside the MCP endpoint's origin and path, and a token endpoint that is down, rate-limited, not found or answers an error page is `remoteUnavailable`, so a refresh during an outage keeps the grant: only an OAuth refusal (a 400, a 401, or a 4xx naming an OAuth error) ends it.
|
|
65
|
+
- `libs/shared` gains the `remote` service, off unless `remote.enabled`: `connectRemote`, `completeRemoteConnection`, `disconnectRemote`, `listRemoteConnections`, the `page/remote/callback` page and `<Remote.Util.Connect>`. A connection is the user's own OAuth grant at the other server, stored sealed; `remoteService.sources(account, refs)` hands them to the loop.
|
|
66
|
+
|
|
67
|
+
- A connected server's app is drawn in the chat by `<Remote.Zone.Screen>` (the server's script-less HTML for an app it declares `{ static: true }`, in a frame that runs no script) or `<Remote.Zone.View>` (its MCP Apps view, scripts on, no origin, under a policy that lets its script open no connection and load images, styles, fonts and media only from that server). `McpAppHost` in `akanjs/webkit` is the host half of the MCP Apps bridge the view talks to. `remoteScreen`, `remoteView` and `callRemoteView` serve them, each limited to what that server lists to the user. A card's open link, and a link a view asks the page to open, is followed only when it is https on that server's own origin.
|
|
68
|
+
|
|
69
|
+
Nothing changes for a request without `remotes`.
|
|
70
|
+
|
|
59
71
|
- 2da2adc: `agentService.loop` takes `toolkits`, so a run over a large catalogue no longer sends every tool definition every round.
|
|
60
72
|
|
|
61
73
|
- **Shape.** `toolkits: { calendar: { description: "Read and edit the org calendar", tools: ["eventListInOrg", "updateEvent"] } }` groups names of `allow`. A tool in no toolkit is the core and is listed every round. `allow` still caps every toolkit.
|
|
@@ -140,6 +152,15 @@
|
|
|
140
152
|
- `use-agentic`'s `RunnerEvent` error gains an optional `code`. `httpRunner` reads it from a stream's error event and keeps it only when it is a dictionary key or one camelCase token. A failure answered before the stream opens is named by its JSON body's bounded code, whether or not the body carries a message, else by its status. A 401 or 403 takes no dictionary key there either, so a refusal or a 5xx reads the code a streamed `error` event names for it. WIRE.md states that rule, and the two cases where the akan server still names a failure differently.
|
|
141
153
|
- The in-page chat keeps the key as `code` after translating the message. The session records it on the failed assistant message as `ChatMessage.errorCode`, which a host reads and the transcript never sends back.
|
|
142
154
|
|
|
155
|
+
- fd76e6f: A page app can declare `{ static: true }` and send a host that asks its element as script-less HTML.
|
|
156
|
+
|
|
157
|
+
- `page().app(name, description, load, { static: true })` marks the app's tool `_meta["akanjs/static"]: true`, with or without a view, wherever the server renders pages.
|
|
158
|
+
- A `tools/call` on that tool whose `params._meta["akanjs/render"]` is `"html"` gets the usual result plus an embedded `text/html` resource `ui://<app>/static/<name>`: the element drawn under the caller's own credential after the route guards, inside the root layout's `McpAppRoot`, with the layout's theme, a `<base>` at the web origin, the stylesheet, every Suspense boundary resolved in place, and no `<script>`. The Flight payload never reaches the document.
|
|
159
|
+
- The HTML also leaves out event handlers, embedded documents, `<noscript>`, refreshes, link animations and `javascript:` links; a formula that carries a handler or a link is sent with no HTML. The whole draw, the page's `load` included, ends within 10 seconds: past that the call answers that the page failed to load.
|
|
160
|
+
- No HTML is sent, and the call answers exactly as before, when the guards refuse, the drawing fails or passes 1 MB, the body is empty or only a fallback, or a component needs a browser. `lazy(…, { ssr: false })` says so itself; any other component calls the new `needsBrowser()` from `akanjs/webkit` while it renders.
|
|
161
|
+
|
|
162
|
+
**Upgrading.** No step is needed: `PageDefinition.app()` takes an optional fourth argument, and `RoutePromptMeta`, `PagePromptEntry`, `PagePromptSource` and `AkanRequestStore` each gain an optional member.
|
|
163
|
+
|
|
143
164
|
- 0a81afa: A generated `<model>` or `light<Model>` read asked for an id that does not exist now logs its 404 at debug, not as an ERROR line. A page guard that checks a document exists, such as `await fetch.memo(memoId)`, used to send every stale link, crawler hit or made-up id to error alerts. The caller still gets the same 404 `base.error.documentNotFound`, and OpenAPI and the MCP catalogue are unchanged.
|
|
144
165
|
|
|
145
166
|
Only the miss of the document the read was asked for, by its model and the call's id, is quieted. Every other missing document still logs as an error, including one inside that same read:
|
|
@@ -22,6 +22,7 @@ interface PageApp {
|
|
|
22
22
|
name: string;
|
|
23
23
|
description: string;
|
|
24
24
|
load: (args: never) => PromiseOrObject<ReactNode>;
|
|
25
|
+
static: boolean;
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
/** `never` for a name the page's render already receives, so a clash fails to compile as well as at definition. */
|
|
@@ -71,12 +72,14 @@ export class PageDefinition<
|
|
|
71
72
|
/**
|
|
72
73
|
* Publishes one component of this screen as an MCP App: a read-only tool whose arguments are the page's `.param()`
|
|
73
74
|
* and `.search()`, and whose result a host draws with `load`'s element. `load` may only query. On the web the
|
|
74
|
-
* element arrives as the render argument `name`. English description.
|
|
75
|
+
* element arrives as the render argument `name`. English description. `static: true` lets a host that runs no
|
|
76
|
+
* script ask the call for the element as HTML, drawn once on the server.
|
|
75
77
|
*/
|
|
76
78
|
app<Name extends string>(
|
|
77
79
|
name: Name & FreeName<Name, Args & Apps>,
|
|
78
80
|
description: string,
|
|
79
81
|
load: (args: RouteBaseArgs & Args) => PromiseOrObject<ReactNode>,
|
|
82
|
+
option: { static?: boolean } = {},
|
|
80
83
|
) {
|
|
81
84
|
PageDefinition.#assertEntry("app", name, description);
|
|
82
85
|
if (name === "lang")
|
|
@@ -87,7 +90,7 @@ export class PageDefinition<
|
|
|
87
90
|
);
|
|
88
91
|
if (this.#prompt?.name === name)
|
|
89
92
|
throw new Error(`[route-convention] page() names "${name}" as both an app and its prompt; MCP lists both`);
|
|
90
|
-
this.#apps.push({ name, description, load: load as PageApp["load"] });
|
|
93
|
+
this.#apps.push({ name, description, load: load as PageApp["load"], static: option.static === true });
|
|
91
94
|
return this as unknown as PageDefinition<Args, Apps & { [Key in Name]: ReactNode }>;
|
|
92
95
|
}
|
|
93
96
|
|
|
@@ -101,7 +104,12 @@ export class PageDefinition<
|
|
|
101
104
|
}
|
|
102
105
|
|
|
103
106
|
get appMetas(): RoutePromptMeta[] {
|
|
104
|
-
return this.#apps.map((
|
|
107
|
+
return this.#apps.map((app) => ({
|
|
108
|
+
name: app.name,
|
|
109
|
+
description: app.description,
|
|
110
|
+
arguments: this.#entryArguments(),
|
|
111
|
+
...(app.static ? { static: true } : {}),
|
|
112
|
+
}));
|
|
105
113
|
}
|
|
106
114
|
|
|
107
115
|
/** One app's element for these args, alone: what an MCP call runs after the route guards, and its view draws. */
|
package/fetch/requestStorage.ts
CHANGED
package/package.json
CHANGED
package/server/index.ts
CHANGED
|
@@ -227,6 +227,28 @@ export {
|
|
|
227
227
|
WebProxyRunner,
|
|
228
228
|
type WebProxyRunResult,
|
|
229
229
|
} from "./proxy";
|
|
230
|
+
export {
|
|
231
|
+
type RemoteAccess,
|
|
232
|
+
type RemoteAddressLookup,
|
|
233
|
+
type RemoteAuthServer,
|
|
234
|
+
type RemoteClient,
|
|
235
|
+
RemoteError,
|
|
236
|
+
type RemoteErrorCode,
|
|
237
|
+
RemoteFetch,
|
|
238
|
+
type RemoteFetchOptions,
|
|
239
|
+
RemoteMcp,
|
|
240
|
+
type RemoteMcpCallResult,
|
|
241
|
+
type RemoteMcpContent,
|
|
242
|
+
type RemoteMcpOptions,
|
|
243
|
+
type RemoteMcpTool,
|
|
244
|
+
RemoteOAuth,
|
|
245
|
+
type RemoteRequest,
|
|
246
|
+
type RemoteResponse,
|
|
247
|
+
type RemoteScreen,
|
|
248
|
+
RemoteSource,
|
|
249
|
+
type RemoteSourceProps,
|
|
250
|
+
type RemoteTokens,
|
|
251
|
+
} from "./remote";
|
|
230
252
|
export type { SessionRefreshHook } from "./sessionRefresh";
|
|
231
253
|
|
|
232
254
|
export {
|
package/server/mcp/McpApps.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { bearerTokenOf, decodeJwtPayload } from "akanjs/common";
|
|
|
3
3
|
import type { PromptContent, PromptMessage } from "../../signal/mcp/Msg";
|
|
4
4
|
import {
|
|
5
5
|
MCP_APP_META,
|
|
6
|
+
MCP_STATIC_APP_META,
|
|
6
7
|
MCP_UI_EXTENSION,
|
|
7
8
|
MCP_UI_LEGACY_RESOURCE_URI,
|
|
8
9
|
MCP_UI_MIME_TYPE,
|
|
@@ -23,6 +24,8 @@ export interface McpAppShellSource {
|
|
|
23
24
|
interface McpAppsOption {
|
|
24
25
|
/** Every write the view sends is refused before it leaves, as the deployment lists no write to relay it to. */
|
|
25
26
|
readOnly?: boolean;
|
|
27
|
+
/** The page source draws a `{ static: true }` app as HTML, so its tool says so and answers a host that asks. */
|
|
28
|
+
staticHtml?: boolean;
|
|
26
29
|
}
|
|
27
30
|
|
|
28
31
|
export class McpApps {
|
|
@@ -33,16 +36,26 @@ export class McpApps {
|
|
|
33
36
|
|
|
34
37
|
readonly #shell: McpAppShellSource | null;
|
|
35
38
|
readonly #readOnly: boolean;
|
|
39
|
+
readonly #staticHtml: boolean;
|
|
36
40
|
|
|
37
|
-
constructor(shell: McpAppShellSource | null, { readOnly = false }: McpAppsOption = {}) {
|
|
41
|
+
constructor(shell: McpAppShellSource | null, { readOnly = false, staticHtml = false }: McpAppsOption = {}) {
|
|
38
42
|
this.#shell = shell;
|
|
39
43
|
this.#readOnly = readOnly;
|
|
44
|
+
this.#staticHtml = staticHtml;
|
|
40
45
|
}
|
|
41
46
|
|
|
42
47
|
get rendersUi() {
|
|
43
48
|
return this.#shell !== null;
|
|
44
49
|
}
|
|
45
50
|
|
|
51
|
+
drawsHtml(entry: PagePromptEntry, params: Record<string, unknown>) {
|
|
52
|
+
if (!this.#staticHtml || entry.kind !== "app" || !entry.static) return false;
|
|
53
|
+
const meta = params._meta;
|
|
54
|
+
return (
|
|
55
|
+
!!meta && typeof meta === "object" && (meta as Record<string, unknown>)[MCP_STATIC_APP_META.render] === "html"
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
46
59
|
static declaresUi(capabilities: unknown) {
|
|
47
60
|
if (!capabilities || typeof capabilities !== "object") return false;
|
|
48
61
|
const extensions = (capabilities as { extensions?: unknown }).extensions;
|
|
@@ -68,10 +81,14 @@ export class McpApps {
|
|
|
68
81
|
const tool = { name: entry.name, description: entry.description, inputSchema };
|
|
69
82
|
|
|
70
83
|
if (entry.kind === "prompt") return { ...tool, annotations: { readOnlyHint: false, openWorldHint: false } };
|
|
84
|
+
const _meta = {
|
|
85
|
+
...(this.#shell ? this.#toolMetaOf(this.uriOf(entry.name)) : {}),
|
|
86
|
+
...(this.#staticHtml && entry.static ? { [MCP_STATIC_APP_META.static]: true } : {}),
|
|
87
|
+
};
|
|
71
88
|
return {
|
|
72
89
|
...tool,
|
|
73
90
|
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
74
|
-
...(
|
|
91
|
+
...(Object.keys(_meta).length ? { _meta } : {}),
|
|
75
92
|
};
|
|
76
93
|
}
|
|
77
94
|
|
|
@@ -95,6 +112,10 @@ export class McpApps {
|
|
|
95
112
|
return `${McpApps.scheme}${getEnv().appName.toLowerCase()}/apps/${app}`;
|
|
96
113
|
}
|
|
97
114
|
|
|
115
|
+
staticUriOf(app: string) {
|
|
116
|
+
return `${McpApps.scheme}${getEnv().appName.toLowerCase()}/static/${app}`;
|
|
117
|
+
}
|
|
118
|
+
|
|
98
119
|
async read(uri: string, origin: string): Promise<McpResourceContents | null> {
|
|
99
120
|
const match = McpApps.#appUri.exec(uri);
|
|
100
121
|
const app = match?.[1]?.toLowerCase() === getEnv().appName.toLowerCase() ? match[2] : undefined;
|
|
@@ -109,12 +130,21 @@ export class McpApps {
|
|
|
109
130
|
messages: PromptMessage[],
|
|
110
131
|
webOrigin: string,
|
|
111
132
|
forView: { account: Record<string, unknown> | null } | null,
|
|
133
|
+
html: string | null = null,
|
|
112
134
|
) {
|
|
113
135
|
const url = new URL(run.url);
|
|
114
136
|
const href = `${url.pathname}${url.search}`;
|
|
115
137
|
const content: PromptContent[] = [
|
|
116
138
|
...messages.map((message) => message.content),
|
|
117
139
|
{ type: "text", text: `Open the full screen: ${webOrigin}${href}` },
|
|
140
|
+
...(html === null
|
|
141
|
+
? []
|
|
142
|
+
: [
|
|
143
|
+
{
|
|
144
|
+
type: "resource" as const,
|
|
145
|
+
resource: { uri: this.staticUriOf(entry.name), mimeType: "text/html", text: html },
|
|
146
|
+
},
|
|
147
|
+
]),
|
|
118
148
|
];
|
|
119
149
|
if (entry.kind === "prompt" || !this.#shell || !forView) return { content, isError: false };
|
|
120
150
|
const _meta = {
|
package/server/mcp/McpPages.ts
CHANGED
|
@@ -9,7 +9,14 @@ import {
|
|
|
9
9
|
} from "../../signal/mcp";
|
|
10
10
|
import type { PromptMessage } from "../../signal/mcp/Msg";
|
|
11
11
|
import type { McpPrompt } from "../../signal/mcp/mcpProtocol";
|
|
12
|
-
import type {
|
|
12
|
+
import type {
|
|
13
|
+
PagePromptEntry,
|
|
14
|
+
PagePromptRefusal,
|
|
15
|
+
PagePromptRender,
|
|
16
|
+
PagePromptRun,
|
|
17
|
+
PagePromptRunInput,
|
|
18
|
+
PagePromptSource,
|
|
19
|
+
} from "../../signal/mcp/pagePrompt";
|
|
13
20
|
import { McpApps } from "./McpApps";
|
|
14
21
|
import { McpAuthRequiredError, type McpDispatcher } from "./McpDispatcher";
|
|
15
22
|
import type { McpUiSession } from "./McpUiSession";
|
|
@@ -37,7 +44,7 @@ interface McpPageCall {
|
|
|
37
44
|
export type McpPageRun =
|
|
38
45
|
| { badArguments: true }
|
|
39
46
|
| { refusal: string; failure: McpFailure }
|
|
40
|
-
| { run: Extract<PagePromptRun, { ok: true }> | null; messages: PromptMessage[] };
|
|
47
|
+
| { run: Extract<PagePromptRun, { ok: true }> | null; messages: PromptMessage[]; html?: string | null };
|
|
41
48
|
|
|
42
49
|
export class McpPages {
|
|
43
50
|
static readonly listWaitMs = 1_000;
|
|
@@ -105,7 +112,8 @@ export class McpPages {
|
|
|
105
112
|
args: Record<string, unknown> | null,
|
|
106
113
|
): Promise<{ badArguments: true } | { result: object }> {
|
|
107
114
|
const apps = this.#props.apps;
|
|
108
|
-
const
|
|
115
|
+
const origin = this.#props.publicOrigin(call.req);
|
|
116
|
+
const page = await this.run(call, document, entry, args, apps?.drawsHtml(entry, call.params) ? origin : null);
|
|
109
117
|
if ("badArguments" in page) return page;
|
|
110
118
|
if ("refusal" in page)
|
|
111
119
|
return {
|
|
@@ -116,9 +124,8 @@ export class McpPages {
|
|
|
116
124
|
},
|
|
117
125
|
};
|
|
118
126
|
if (!page.run || !apps) return { result: { content: page.messages.map((message) => message.content) } };
|
|
119
|
-
const origin = this.#props.publicOrigin(call.req);
|
|
120
127
|
const forView = call.ui ? { account: McpApps.accountOf(call.req) } : null;
|
|
121
|
-
return { result: apps.resultOf(entry, page.run, page.messages, origin, forView) };
|
|
128
|
+
return { result: apps.resultOf(entry, page.run, page.messages, origin, forView, page.html ?? null) };
|
|
122
129
|
}
|
|
123
130
|
|
|
124
131
|
async run(
|
|
@@ -126,6 +133,7 @@ export class McpPages {
|
|
|
126
133
|
document: McpDocument,
|
|
127
134
|
entry: PagePromptEntry,
|
|
128
135
|
args: Record<string, unknown> | null,
|
|
136
|
+
htmlOrigin: string | null = null,
|
|
129
137
|
): Promise<McpPageRun> {
|
|
130
138
|
const source = this.#props.source;
|
|
131
139
|
const { name } = entry;
|
|
@@ -147,12 +155,16 @@ export class McpPages {
|
|
|
147
155
|
.filter((arg) => arg.required && strings[arg.name] === undefined)
|
|
148
156
|
.map((arg) => arg.name);
|
|
149
157
|
if (missing.length) return { run: null, messages: composer.missing(entry, missing) };
|
|
150
|
-
const run = await
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
158
|
+
const { run, html } = await this.#render(
|
|
159
|
+
source,
|
|
160
|
+
{
|
|
161
|
+
name,
|
|
162
|
+
arguments: strings,
|
|
163
|
+
headers: McpPages.#forwardedHeaders(call.req),
|
|
164
|
+
language: this.#props.language,
|
|
165
|
+
},
|
|
166
|
+
htmlOrigin,
|
|
167
|
+
);
|
|
156
168
|
if (!run.ok) {
|
|
157
169
|
|
|
158
170
|
const gated = run.reason === "redirect" || run.reason === "forbidden";
|
|
@@ -168,7 +180,17 @@ export class McpPages {
|
|
|
168
180
|
: MCP_SCREEN_REFUSAL.failed;
|
|
169
181
|
return { refusal: message, failure: McpPages.#failureOf(gated ? "forbidden" : run.reason) };
|
|
170
182
|
}
|
|
171
|
-
return { run, messages: await composer.compose(entry, run) };
|
|
183
|
+
return { run, messages: await composer.compose(entry, run), html };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async #render(source: PagePromptSource, input: PagePromptRunInput, origin: string | null): Promise<PagePromptRender> {
|
|
187
|
+
if (origin === null || !source.render) return { run: await source.run(input), html: null };
|
|
188
|
+
try {
|
|
189
|
+
return await source.render({ ...input, origin });
|
|
190
|
+
} catch (error) {
|
|
191
|
+
const message = `static app "${input.name}" sent no HTML: ${error instanceof Error ? error.message : error}`;
|
|
192
|
+
return { run: { ok: false, reason: "error", message }, html: null };
|
|
193
|
+
}
|
|
172
194
|
}
|
|
173
195
|
|
|
174
196
|
static #failureOf(reason: PagePromptRefusal): McpFailure {
|
package/server/mcp/McpRouter.ts
CHANGED
|
@@ -112,7 +112,9 @@ export class McpRouter {
|
|
|
112
112
|
this.#dispatcher = new McpDispatcher({ ...props, legacyTextBlock, language: props.language ?? defaultLanguage });
|
|
113
113
|
this.#auth = new McpAuth({ ...props.auth, path: props.path ?? "/mcp" });
|
|
114
114
|
this.#apps =
|
|
115
|
-
props.apps && props.pagePrompts
|
|
115
|
+
props.apps && props.pagePrompts
|
|
116
|
+
? new McpApps(props.appShell ?? null, { readOnly: props.readOnly, staticHtml: !!props.pagePrompts.render })
|
|
117
|
+
: null;
|
|
116
118
|
const cache = props.registry.adaptor.get(CacheAdaptorRole) as (McpSharedCounter & McpUiSessionStore) | undefined;
|
|
117
119
|
this.#pages = new McpPages({
|
|
118
120
|
source: props.pagePrompts,
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { lookup } from "node:dns/promises";
|
|
2
|
+
import { TrustedProxy } from "akanjs/common";
|
|
3
|
+
import { RemoteError } from "./remoteError";
|
|
4
|
+
|
|
5
|
+
export type RemoteAddressLookup = (hostname: string) => Promise<{ address: string; family?: number }[]>;
|
|
6
|
+
|
|
7
|
+
export interface RemoteFetchOptions {
|
|
8
|
+
/** Reaches loopback and private addresses, over plain http too. For a developer's machine and tests only. */
|
|
9
|
+
allowPrivate?: boolean;
|
|
10
|
+
lookup?: RemoteAddressLookup;
|
|
11
|
+
fetchImpl?: (input: URL, init: RequestInit & { tls?: { serverName: string } }) => Promise<Response>;
|
|
12
|
+
timeoutMs?: number;
|
|
13
|
+
maxBytes?: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface RemoteRequest {
|
|
17
|
+
method?: "GET" | "POST";
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
body?: string;
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
maxBytes?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface RemoteResponse {
|
|
25
|
+
status: number;
|
|
26
|
+
headers: Headers;
|
|
27
|
+
text: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export class RemoteFetch {
|
|
31
|
+
static readonly timeoutMs = 30_000;
|
|
32
|
+
static readonly maxBytes = 2 * 1024 * 1024;
|
|
33
|
+
|
|
34
|
+
readonly #options: RemoteFetchOptions;
|
|
35
|
+
|
|
36
|
+
constructor(options: RemoteFetchOptions = {}) {
|
|
37
|
+
this.#options = options;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
get allowsPrivate(): boolean {
|
|
41
|
+
return this.#options.allowPrivate === true;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The url as this fetch would take it, or a `RemoteError` naming why not. */
|
|
45
|
+
parse(input: string | URL): URL {
|
|
46
|
+
const url = typeof input === "string" ? URL.parse(input) : new URL(input.href);
|
|
47
|
+
if (!url) throw new RemoteError("remoteUrlRejected", "That is not a URL.");
|
|
48
|
+
const plain = url.protocol === "http:" && this.allowsPrivate;
|
|
49
|
+
if (url.protocol !== "https:" && !plain) throw new RemoteError("remoteUrlRejected", "The URL must be https.");
|
|
50
|
+
if (url.username || url.password)
|
|
51
|
+
throw new RemoteError("remoteUrlRejected", "The URL may not carry a user name or a password.");
|
|
52
|
+
return url;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async send(input: string | URL, request: RemoteRequest = {}): Promise<RemoteResponse> {
|
|
56
|
+
const url = this.parse(input);
|
|
57
|
+
const { timeoutMs = RemoteFetch.timeoutMs, fetchImpl = fetch } = this.#options;
|
|
58
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
59
|
+
const signal = request.signal ? AbortSignal.any([request.signal, timeout]) : timeout;
|
|
60
|
+
try {
|
|
61
|
+
const { target, tls } = await this.#pinned(url, signal);
|
|
62
|
+
const headers = new Headers(request.headers);
|
|
63
|
+
if (target.host !== url.host) headers.set("host", url.host);
|
|
64
|
+
const response = await fetchImpl(target, {
|
|
65
|
+
method: request.method ?? "GET",
|
|
66
|
+
headers,
|
|
67
|
+
...(request.body === undefined ? {} : { body: request.body }),
|
|
68
|
+
redirect: "manual",
|
|
69
|
+
signal,
|
|
70
|
+
...(tls ? { tls } : {}),
|
|
71
|
+
});
|
|
72
|
+
if (response.status >= 300 && response.status < 400) {
|
|
73
|
+
await response.body?.cancel().catch(() => undefined);
|
|
74
|
+
throw new RemoteError("remoteUrlRejected", `${url.host} answered with a redirect, which is not followed.`);
|
|
75
|
+
}
|
|
76
|
+
const maxBytes = request.maxBytes ?? this.#options.maxBytes ?? RemoteFetch.maxBytes;
|
|
77
|
+
const text = await RemoteFetch.#read(response, maxBytes, signal);
|
|
78
|
+
return { status: response.status, headers: response.headers, text };
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (error instanceof RemoteError || request.signal?.aborted) throw error;
|
|
81
|
+
throw new RemoteError("remoteUnavailable", `${url.host} did not answer: ${RemoteFetch.#reason(error)}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async json(input: string | URL, request: RemoteRequest = {}): Promise<{ status: number; body: unknown }> {
|
|
86
|
+
const { status, text } = await this.send(input, {
|
|
87
|
+
...request,
|
|
88
|
+
headers: { accept: "application/json", ...request.headers },
|
|
89
|
+
});
|
|
90
|
+
try {
|
|
91
|
+
return { status, body: text.trim() ? JSON.parse(text) : null };
|
|
92
|
+
} catch {
|
|
93
|
+
return { status, body: null };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async #pinned(url: URL, signal: AbortSignal): Promise<{ target: URL; tls?: { serverName: string } }> {
|
|
98
|
+
if (this.allowsPrivate) return { target: url };
|
|
99
|
+
const host = url.hostname.startsWith("[") ? url.hostname.slice(1, -1) : url.hostname;
|
|
100
|
+
const literal = /^\d+\.\d+\.\d+\.\d+$/.test(host) || host.includes(":");
|
|
101
|
+
if (literal) {
|
|
102
|
+
if (TrustedProxy.isPrivateAddress(host))
|
|
103
|
+
throw new RemoteError("remoteUrlRejected", "The URL points into a private network.");
|
|
104
|
+
return { target: url };
|
|
105
|
+
}
|
|
106
|
+
const resolve = this.#options.lookup ?? RemoteFetch.#lookup;
|
|
107
|
+
const addresses = await RemoteFetch.#until(
|
|
108
|
+
signal,
|
|
109
|
+
resolve(host).catch(() => []),
|
|
110
|
+
);
|
|
111
|
+
if (!addresses.length) throw new RemoteError("remoteUrlRejected", `${host} does not resolve.`);
|
|
112
|
+
|
|
113
|
+
if (addresses.some(({ address }) => TrustedProxy.isPrivateAddress(address)))
|
|
114
|
+
throw new RemoteError("remoteUrlRejected", "The URL points into a private network.");
|
|
115
|
+
const { address } = addresses.find(({ family }) => family === 4) ?? addresses[0];
|
|
116
|
+
const target = new URL(url.href);
|
|
117
|
+
target.hostname = address.includes(":") ? `[${address}]` : address;
|
|
118
|
+
return { target, tls: { serverName: host } };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
static readonly #lookup: RemoteAddressLookup = async (hostname) => await lookup(hostname, { all: true });
|
|
122
|
+
|
|
123
|
+
static async #read(response: Response, maxBytes: number, signal: AbortSignal): Promise<string> {
|
|
124
|
+
if (Number(response.headers.get("content-length")) > maxBytes) {
|
|
125
|
+
await response.body?.cancel().catch(() => undefined);
|
|
126
|
+
throw new RemoteError("remoteTooLarge", `The answer is past ${maxBytes} bytes.`);
|
|
127
|
+
}
|
|
128
|
+
const reader = response.body?.getReader();
|
|
129
|
+
if (!reader) return "";
|
|
130
|
+
const chunks: Uint8Array[] = [];
|
|
131
|
+
let bytes = 0;
|
|
132
|
+
const next = () =>
|
|
133
|
+
RemoteFetch.#until(signal, reader.read()).catch(async (error: unknown) => {
|
|
134
|
+
await reader.cancel().catch(() => undefined);
|
|
135
|
+
throw error;
|
|
136
|
+
});
|
|
137
|
+
for (let chunk = await next(); !chunk.done; chunk = await next()) {
|
|
138
|
+
bytes += chunk.value.byteLength;
|
|
139
|
+
if (bytes > maxBytes) {
|
|
140
|
+
await reader.cancel().catch(() => undefined);
|
|
141
|
+
throw new RemoteError("remoteTooLarge", `The answer is past ${maxBytes} bytes.`);
|
|
142
|
+
}
|
|
143
|
+
chunks.push(chunk.value);
|
|
144
|
+
}
|
|
145
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
static #until<T>(signal: AbortSignal, work: Promise<T>): Promise<T> {
|
|
149
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
150
|
+
return new Promise<T>((resolve, reject) => {
|
|
151
|
+
const stop = () => reject(signal.reason);
|
|
152
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
153
|
+
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
static #reason(error: unknown): string {
|
|
158
|
+
if (error instanceof Error && error.name === "TimeoutError") return "timed out";
|
|
159
|
+
return error instanceof Error ? error.message : String(error);
|
|
160
|
+
}
|
|
161
|
+
}
|