@dudko.dev/agent-web-react 0.0.17 → 0.0.19

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/dist/mcp.d.ts ADDED
@@ -0,0 +1,265 @@
1
+ import { AgentToolSet } from '@dudko.dev/agent-web';
2
+
3
+ /**
4
+ * Structural types for the core's OPTIONAL `@dudko.dev/agent-web/mcp` subpath.
5
+ *
6
+ * The subpath is loaded with a dynamic import and typed here rather than
7
+ * imported, for two reasons: it drags in `@modelcontextprotocol/sdk` (an
8
+ * optional peer of the core, which apps without MCP must not have to install),
9
+ * and the OAuth half only exists in newer cores while this package supports
10
+ * `@dudko.dev/agent-web >= 0.0.6`. `useMcp` feature-detects at runtime and
11
+ * reports `oauthSupported: false` on an older core instead of crashing.
12
+ */
13
+ interface McpCatalogEntry {
14
+ name: string;
15
+ description: string;
16
+ server: string;
17
+ /** The server marked the tool read-only (newer cores). */
18
+ readOnly?: boolean;
19
+ }
20
+ interface McpServerResult {
21
+ name: string;
22
+ connected: boolean;
23
+ error?: string;
24
+ needsAuthorization?: boolean;
25
+ }
26
+ interface ConnectedMcp {
27
+ tools: AgentToolSet;
28
+ catalog: McpCatalogEntry[];
29
+ results: McpServerResult[];
30
+ refreshServer?: (name: string) => Promise<void>;
31
+ close: () => Promise<void>;
32
+ }
33
+ interface McpHttpServerConfig {
34
+ url: string;
35
+ headers?: Record<string, string>;
36
+ authProvider?: unknown;
37
+ /** Per-server connect deadline (newer cores; ignored by older ones). */
38
+ connectTimeoutMs?: number;
39
+ }
40
+ interface McpOAuthCallback {
41
+ code?: string;
42
+ state?: string;
43
+ error?: string;
44
+ errorDescription?: string;
45
+ }
46
+ interface BrowserOAuthProvider {
47
+ serverUrl: string;
48
+ authorizationUrl?: URL;
49
+ isAuthorized(): Promise<boolean>;
50
+ reset(): Promise<void>;
51
+ }
52
+ interface BrowserOAuthProviderOptions {
53
+ serverUrl: string;
54
+ redirectUrl: string;
55
+ clientName?: string;
56
+ scope?: string;
57
+ }
58
+ /** The shape of the subpath module, as far as this package uses it. */
59
+ interface McpModule {
60
+ connectMcpHttp: (servers: Record<string, McpHttpServerConfig>, opts?: {
61
+ clientName?: string;
62
+ onLog?: (level: string, message: string) => void;
63
+ connectTimeoutMs?: number;
64
+ }) => Promise<ConnectedMcp>;
65
+ BrowserOAuthProvider?: new (opts: BrowserOAuthProviderOptions) => BrowserOAuthProvider;
66
+ readOAuthCallback?: (input?: string | URL) => McpOAuthCallback | undefined;
67
+ finishMcpOAuth?: (provider: BrowserOAuthProvider, callback: McpOAuthCallback) => Promise<void>;
68
+ /**
69
+ * The SDK's error class, re-exported by the core so an authorization failure
70
+ * can be recognised by identity. Absent on cores older than 0.0.12.
71
+ */
72
+ UnauthorizedError?: new (message?: string) => Error;
73
+ }
74
+
75
+ type McpStatus = 'idle' | 'connecting' | 'connected' | 'needs-authorization' | 'error';
76
+ interface McpConnectOptions {
77
+ /** The server's StreamableHTTP endpoint. */
78
+ url: string;
79
+ /** Prefix for the discovered tool names ("<name>__<tool>"). Default 'mcp'. */
80
+ name?: string;
81
+ /** Static headers, e.g. `{ Authorization: 'Bearer …' }`. Ignored when `oauth` is set. */
82
+ headers?: Record<string, string>;
83
+ /**
84
+ * Authenticate with OAuth 2.1 + dynamic client registration. Requires a core
85
+ * that ships the OAuth provider; check `oauthSupported` before offering it.
86
+ */
87
+ oauth?: boolean | {
88
+ redirectUrl?: string;
89
+ scope?: string;
90
+ clientName?: string;
91
+ };
92
+ }
93
+ interface UseMcpOptions {
94
+ /** Client name reported to the MCP server during initialize. */
95
+ clientName?: string;
96
+ /** Called with connector log lines — handy while debugging a server. */
97
+ onLog?: (level: string, message: string) => void;
98
+ }
99
+ interface UseMcpReturn {
100
+ status: McpStatus;
101
+ /** Merge into `BrowserAgentConfig.tools` once `status === 'connected'`. */
102
+ tools?: AgentToolSet;
103
+ catalog: McpCatalogEntry[];
104
+ error?: string;
105
+ /** Where to send the user when `status === 'needs-authorization'`. */
106
+ authorizationUrl?: string;
107
+ /**
108
+ * Whether the installed core exposes the OAuth API. `undefined` until the
109
+ * optional subpath has been loaded once — call `checkOAuthSupport()` to
110
+ * resolve it before offering OAuth in your UI.
111
+ */
112
+ oauthSupported?: boolean;
113
+ /** True while an OAuth redirect is being finished on mount. */
114
+ completingAuthorization: boolean;
115
+ connect: (options: McpConnectOptions) => Promise<void>;
116
+ disconnect: () => Promise<void>;
117
+ /** Navigate to the authorization server. Call it from a user gesture. */
118
+ authorize: () => void;
119
+ /** Drop the stored tokens and dynamic registration for the current server. */
120
+ forgetAuthorization: () => Promise<void>;
121
+ /** Load the optional subpath and report whether it can do OAuth. */
122
+ checkOAuthSupport: () => Promise<boolean>;
123
+ }
124
+ /** Map a single server's connect outcome onto the hook's status. Pure. */
125
+ declare const describeMcpResult: (result: McpServerResult | undefined) => {
126
+ status: McpStatus;
127
+ error?: string;
128
+ };
129
+ /**
130
+ * Read the authorization-code parameters out of a URL **synchronously**.
131
+ *
132
+ * The core exports an equivalent, but it lives behind a dynamic import: by the
133
+ * time that import resolves, React has flushed the rest of the app's effects,
134
+ * and any one of them may have rewritten `location` (the demo's own view
135
+ * router did exactly that). The callback has to be captured before the first
136
+ * await, so this parser is duplicated here on purpose.
137
+ *
138
+ * Reads the query string and, for hash-routed apps, the fragment. Returns
139
+ * undefined when neither a `code` nor an `error` is present.
140
+ */
141
+ declare const readCallbackParams: (href?: string) => McpOAuthCallback | undefined;
142
+ /**
143
+ * Remove the OAuth response parameters from a URL, leaving the rest intact —
144
+ * query string and fragment alike. The code is single-use and lands in history,
145
+ * referrers and screenshots, so it goes as soon as it has been read.
146
+ */
147
+ declare const stripOAuthParams: (href: string) => string;
148
+ declare const claimOAuthCallback: (callback: McpOAuthCallback) => boolean;
149
+ /**
150
+ * Did this error come from the server refusing our authorization?
151
+ *
152
+ * Identity, not strings: the SDK's `UnauthorizedError` never assigns
153
+ * `this.name` (so it reads as "Error"), and its message would also match a
154
+ * tool whose own error text mentions "unauthorized" — the connector throws a
155
+ * failing tool's text verbatim. The class is re-exported by the core's `./mcp`
156
+ * subpath for exactly this; `constructor.name` is the fallback for a core too
157
+ * old to export it.
158
+ */
159
+ declare const isUnauthorizedError: (err: unknown, mod?: McpModule) => boolean;
160
+ /**
161
+ * Connect the browser agent to a remote MCP server the user names at runtime —
162
+ * static header, or full OAuth 2.1 with dynamic client registration.
163
+ *
164
+ * The OAuth round-trip leaves the page, so the hook persists what it needs to
165
+ * resume: on mount it detects `?code=…`, finishes the exchange, cleans the URL
166
+ * and reconnects, all before the app renders anything MCP-related.
167
+ *
168
+ * ```tsx
169
+ * const mcp = useMcp()
170
+ * // await mcp.connect({ url, oauth: true })
171
+ * // mcp.status === 'needs-authorization' && <button onClick={mcp.authorize}>Authorize</button>
172
+ * // <AgentProvider config={{ model, tools: { ...local, ...mcp.tools } }}>
173
+ * ```
174
+ */
175
+ declare const useMcp: (options?: UseMcpOptions) => UseMcpReturn;
176
+
177
+ type McpAuthMode = 'none' | 'bearer' | 'oauth';
178
+ /** One server the user wants connected. */
179
+ interface McpServerSpec {
180
+ /**
181
+ * Unique name; also the tool prefix ("<name>__<tool>"). Sanitised to
182
+ * `[a-zA-Z0-9_-]`; a taken name gets a numeric suffix.
183
+ */
184
+ name: string;
185
+ /** The server's StreamableHTTP endpoint. */
186
+ url: string;
187
+ auth?: McpAuthMode;
188
+ /** Bearer token for `auth: 'bearer'` — kept in memory only, never persisted. */
189
+ token?: string;
190
+ /** OAuth details for `auth: 'oauth'`. */
191
+ oauth?: {
192
+ redirectUrl?: string;
193
+ scope?: string;
194
+ clientName?: string;
195
+ };
196
+ }
197
+ /** A server's live state. */
198
+ interface McpServerView {
199
+ name: string;
200
+ url: string;
201
+ auth: McpAuthMode;
202
+ status: McpStatus;
203
+ error?: string;
204
+ /** Where to send the user when `status === 'needs-authorization'`. */
205
+ authorizationUrl?: string;
206
+ catalog: McpCatalogEntry[];
207
+ }
208
+ interface UseMcpServersOptions extends UseMcpOptions {
209
+ /**
210
+ * Remember the server list (never tokens) in localStorage so it survives a
211
+ * reload — and the OAuth redirect, which IS a reload (default true).
212
+ */
213
+ persist?: boolean;
214
+ /** localStorage key of the list (default 'agent-web-react:mcp-servers'). */
215
+ storageKey?: string;
216
+ /** Reconnect remembered servers on mount (default true). Bearer servers wait for their token. */
217
+ autoConnect?: boolean;
218
+ /** Per-server connect deadline in ms (default: the core's, 30 s). */
219
+ connectTimeoutMs?: number;
220
+ }
221
+ interface UseMcpServersReturn {
222
+ servers: McpServerView[];
223
+ /** Tools of every connected server, merged — pass to `BrowserAgentConfig.tools`. */
224
+ tools: AgentToolSet;
225
+ /** Catalogue of every connected server, merged. */
226
+ catalog: McpCatalogEntry[];
227
+ connectedCount: number;
228
+ /** True while an OAuth redirect is being finished on mount. */
229
+ completingAuthorization: boolean;
230
+ /** Whether the installed core can do OAuth (undefined until checked). */
231
+ oauthSupported?: boolean;
232
+ checkOAuthSupport: () => Promise<boolean>;
233
+ /** Add (or replace, by name) a server and connect it. Resolves with the final name. */
234
+ add: (spec: McpServerSpec) => Promise<string>;
235
+ /** Disconnect and forget a server. */
236
+ remove: (name: string) => Promise<void>;
237
+ /** Connect again — optionally with a fresh bearer token. */
238
+ reconnect: (name: string, token?: string) => Promise<void>;
239
+ /** Navigate to the server's authorization page. Call it from a user gesture. */
240
+ authorize: (name: string) => void;
241
+ /** Drop a server's stored OAuth tokens and registration. */
242
+ forgetAuthorization: (name: string) => Promise<void>;
243
+ }
244
+ /**
245
+ * Connect the browser agent to SEVERAL remote MCP servers at once, each with
246
+ * its own auth (none, a bearer token, or OAuth 2.1 + dynamic registration).
247
+ * Every server is its own connection — adding or removing one never touches
248
+ * the others — and their tools merge into one `tools` set, prefixed by server
249
+ * name. The list is remembered across reloads (tokens excepted), and an OAuth
250
+ * round-trip resumes on return.
251
+ *
252
+ * ```tsx
253
+ * const mcp = useMcpServers()
254
+ * // await mcp.add({ name: 'github', url, auth: 'oauth' })
255
+ * // await mcp.add({ name: 'docs', url, auth: 'bearer', token })
256
+ * const agent = useAgent({ model, tools: { ...local, ...mcp.tools } }, { deps: [mcp.tools] })
257
+ * ```
258
+ *
259
+ * With many servers the merged catalogue can reach hundreds of tools; the core
260
+ * switches to tool search above `toolSearchThreshold` automatically.
261
+ */
262
+ declare const useMcpServers: (options?: UseMcpServersOptions) => UseMcpServersReturn;
263
+
264
+ export { claimOAuthCallback, describeMcpResult, isUnauthorizedError, readCallbackParams, stripOAuthParams, useMcp, useMcpServers };
265
+ export type { ConnectedMcp, McpAuthMode, McpCatalogEntry, McpConnectOptions, McpModule, McpOAuthCallback, McpServerResult, McpServerSpec, McpServerView, McpStatus, UseMcpOptions, UseMcpReturn, UseMcpServersOptions, UseMcpServersReturn };