@usemcpkit/core 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,10 +1,12 @@
1
1
  # @usemcpkit/core
2
2
 
3
- Library behind mcpkit: the manifest format and its validation, the server SDK (`defineServer`, `defineTool`,
4
- `defineUI`), the HTTP executor with response mapping, and auth (fallbacks, OAuth 2.0 PKCE, the credentials form
5
- contract). Published to npm. It contains no per-provider code: a server differs from another only in its manifest.
3
+ The authoring side of usemcpkit: the manifest format, the server SDK (`defineServer`,
4
+ `defineTool`, `defineUI`), the upstream naming rules (`nameUpstreamTool`) and the credentials form contract the
5
+ page uses (`CREDENTIALS_FORM_API`, the `Credential*` types). Published to npm. It runs nothing: the `usemcpkit`
6
+ binaries (Rust, `apps/runner` and `apps/server`) execute the manifests, sign in and keep the credentials, as
7
+ described below. It contains no per-provider code: a server differs from another only in its manifest.
6
8
 
7
- Public surface: `src/main.ts` (built to `build/mcpkit.core.js` with bundled types in `build/mcpkit.core.d.ts`).
9
+ Public surface: `src/main.ts` (built to `build/usemcpkit.core.js` with bundled types in `build/usemcpkit.core.d.ts`).
8
10
 
9
11
  ## Manifest format
10
12
 
@@ -98,19 +100,19 @@ saying why. `none` can only be the last entry. Leaving out `auth` means no auth.
98
100
  `ui`, see below).
99
101
  Env vars always win, so CI keeps working without a browser.
100
102
 
101
- **Credentials form.** `mcpkit serve` starts a one-off server on `127.0.0.1` (a free port), prints its URL to
103
+ **Credentials form.** `usemcpkit serve` starts a one-off server on `127.0.0.1` (a free port), prints its URL to
102
104
  stderr and opens the browser. Only the page that was opened can answer: the URL carries a session token in its
103
105
  `#fragment` and the server checks it and the `Host` header. Concurrent calls share one form; it closes after
104
106
  an answer, on Cancel, or after 5 minutes. Secrets are saved **only after the API accepts them**, so a typo is never
105
107
  stored.
106
108
 
107
- **Config file.** The hosts and the saved credentials live together in `~/.mcpkit/config.json`, by category, server and host
109
+ **Config file.** The hosts and the saved credentials live together in `~/.usemcpkit/config.json`, by category, server and host
108
110
  (`{ "servers": { "git": { "gitlab": { "hosts": { "git.acme.com": { "secrets": { "GITLAB_TOKEN": "glpat-…" } } }, "projects": { "/work/app": "git.acme.com" } } } } }`),
109
111
  which you can edit by hand. Credentials never cross hosts. With several hosts for one server, the host of a call is, in order:
110
112
  its env var; the host its project (git root) was bound to the first time you answered the form; the saved host the
111
113
  project's `origin` remote points at (servers whose manifest sets `domain.matchGitRemote`, such as GitHub and GitLab);
112
114
  otherwise the form asks, and the answer is remembered for that project. Credentials are plain text, with file mode `0600` in a `0700` directory, the way `gh` and `glab` keep
113
- their tokens. The file carries a `version` (now 2); a file without one is version 1 and, like an older `secrets.json`, is upgraded on first use by the migration list in `auth/config/config-migrations.ts` (a new version is one appended entry), and a file from a newer mcpkit is refused rather than overwritten. There is no password and nothing to unlock. Any program running as your user can read the file, so
115
+ their tokens. The file carries a `version` (now 2); a file without one is version 1 and, like an older `secrets.json`, is upgraded on first use by the migration list in `crates/auth/src/config/config_migrations.rs` (a new version is one appended entry), and a file from a newer usemcpkit is refused rather than overwritten. There is no password and nothing to unlock. Any program running as your user can read the file, so
114
116
  protect your account and disk; to forget a credential, delete its entry or the file. Environment variables always win
115
117
  over the file.
116
118
 
@@ -130,7 +132,7 @@ defineServer({
130
132
  ui: defineUI({
131
133
  inputs: { GITHUB_TOKEN: { label: 'Token', hint: '…', placeholder: 'ghp_…' } },
132
134
  actions: [
133
- { type: 'link', label: 'Create on GitHub ↗', url: 'https://{webHost}/settings/tokens/new?name=mcpkit+{server}' },
135
+ { type: 'link', label: 'Create on GitHub ↗', url: 'https://{webHost}/settings/tokens/new?name=usemcpkit+{server}' },
134
136
  { type: 'cli', label: 'Use GitHub CLI', command: 'gh', args: ['auth', 'token', '--hostname', '{webHost}'] },
135
137
  ],
136
138
  }),
@@ -157,7 +159,7 @@ with a name and the `api` scope.
157
159
 
158
160
  The CLI button is offered only for options with a single field. A domain typed in the form is used once it is valid. An imported token is saved like a
159
161
  typed one: only after the API accepts it. Manifests can be updated remotely (see below), so only use a registry you
160
- trust: its `cli` buttons name the programs mcpkit runs when you click them.
162
+ trust: its `cli` buttons name the programs usemcpkit runs when you click them.
161
163
 
162
164
  **Domain.** A server whose host differs per user (GitHub Enterprise, self-hosted GitLab, Jira...) writes
163
165
  `{domain}` in `baseUrl` and, if it has them, in the OAuth URLs, and declares `domain`:
@@ -183,9 +185,9 @@ user change it (`host[:port][/path]`, no scheme), unless the env var is set.
183
185
  }
184
186
  ```
185
187
 
186
- The sign-in starts on the first tool call that has no working token: `mcpkit serve` prints the URL to stderr
188
+ The sign-in starts on the first tool call that has no working token: `usemcpkit serve` prints the URL to stderr
187
189
  and opens the browser. The redirect goes to `http://127.0.0.1:<port>/callback`, and the authorization code is
188
- exchanged with a S256 code verifier. The token is saved to `~/.mcpkit/tokens.json` (`MCPKIT_HOME` overrides)
190
+ exchanged with a S256 code verifier. The token is saved to `~/.usemcpkit/tokens.json` (`USEMCPKIT_HOME` overrides)
189
191
  with file mode `0600`, together with the entry that issued it. Tool calls send it as a Bearer token and refresh
190
192
  it before it expires. Concurrent calls share one sign-in. If the MCP client gives up waiting, the sign-in still
191
193
  finishes and the next call uses the token.
@@ -6,22 +6,6 @@ export declare type ArgSpec = NameList | NameMapping;
6
6
 
7
7
  export declare const array: (items: JsonSchema, description?: string) => Param;
8
8
 
9
- export declare interface AuthContext {
10
- env: Env;
11
- fetchImpl: typeof fetch;
12
- /** The directory the calling client works in; it picks the host of a server used on several hosts. */
13
- projectDir?: string;
14
- /** Shows the user the URL that starts a browser sign-in; without it a call never signs in. */
15
- onAuthorizationUrl?: (url: string) => void;
16
- /** Credentials saved from the credentials form; env vars win over them. */
17
- secretStore?: SecretStore;
18
- /** Asks the user for a domain and credentials when nothing provided works; without it no form is shown. */
19
- requestCredentials?: (request: CredentialRequest) => Promise<CredentialResponse>;
20
- }
21
-
22
- export declare class AuthError extends Error {
23
- }
24
-
25
9
  export declare type AuthSpec = NoneAuth | BearerAuth | HeaderAuth | QueryAuth | BasicAuth | OAuthAuth;
26
10
 
27
11
  declare interface BasicAuth {
@@ -45,20 +29,6 @@ declare interface BearerAuth {
45
29
 
46
30
  export declare const boolean: (description?: string, options?: ParamOptions) => Param;
47
31
 
48
- /** Expects args already passed through prepareToolArgs and loadFileArgs. */
49
- export declare const buildRequest: (manifest: Manifest, tool: ToolSpec, args: ToolArgs, auth: ResolvedAuth) => HttpRequest;
50
-
51
- /** A command that prints a token on stdout; run without a shell. */
52
- export declare interface CliTokenCommand {
53
- command: string;
54
- args: readonly string[];
55
- }
56
-
57
- export declare const compareVersions: (left: string, right: string) => number;
58
-
59
- /** Plain text in the 0600 config file under the mcpkit home, by server and host, read on every call so all running servers see each other's saves. */
60
- export declare const createFileSecretStore: (env?: Env) => SecretStore;
61
-
62
32
  export declare interface CredentialField {
63
33
  /** The env var that provides this value without the form. */
64
34
  key: string;
@@ -100,9 +70,9 @@ export declare const CREDENTIALS_FORM_API: {
100
70
  readonly import: "/api/import";
101
71
  };
102
72
 
103
- export declare const CREDENTIALS_FORM_SESSION_HEADER = "X-Mcpkit-Session";
73
+ export declare const CREDENTIALS_FORM_SESSION_HEADER = "X-Usemcpkit-Session";
104
74
 
105
- export declare const CREDENTIALS_REQUEST_ELEMENT_ID = "mcpkit-request";
75
+ export declare const CREDENTIALS_REQUEST_ELEMENT_ID = "usemcpkit-request";
106
76
 
107
77
  export declare const DEFAULT_UI_TEXTS: Readonly<UiTexts>;
108
78
 
@@ -149,20 +119,6 @@ export declare interface EditionSpec {
149
119
  hosts: readonly string[];
150
120
  }
151
121
 
152
- export declare type Env = Readonly<Record<string, string | undefined>>;
153
-
154
- export declare interface ExecuteOptions {
155
- fetchImpl?: typeof fetch;
156
- timeoutMs?: number;
157
- env?: Env;
158
- onAuthorizationUrl?: AuthContext["onAuthorizationUrl"];
159
- projectDir?: AuthContext["projectDir"];
160
- secretStore?: AuthContext["secretStore"];
161
- requestCredentials?: AuthContext["requestCredentials"];
162
- }
163
-
164
- export declare const executeTool: (manifest: Manifest, tool: ToolSpec, rawArgs: ToolArgs | undefined, { fetchImpl, timeoutMs, env, ...hooks }?: ExecuteOptions) => Promise<unknown>;
165
-
166
122
  /** Auth whose credentials are provided up front: an env var, a saved value or the credentials form. */
167
123
  export declare type FallbackAuth = Exclude<AuthSpec, InteractiveAuth>;
168
124
 
@@ -182,17 +138,11 @@ export declare type FixedValues = Readonly<Record<string, FixedValue>>;
182
138
  * in the default browser (a webview has no tabs, so `target="_blank"` links go nowhere).
183
139
  */
184
140
  export declare const FORM_WINDOW_BINDINGS: {
185
- readonly close: "mcpkitCloseWindow";
186
- readonly fit: "mcpkitFitWindow";
187
- readonly openLink: "mcpkitOpenLink";
141
+ readonly close: "usemcpkitCloseWindow";
142
+ readonly fit: "usemcpkitFitWindow";
143
+ readonly openLink: "usemcpkitOpenLink";
188
144
  };
189
145
 
190
- /**
191
- * Resolves `a.b.c` paths; a `name[]` segment maps the rest of the path over an array.
192
- * The return type is declared because TypeScript cannot infer it for this recursive function.
193
- */
194
- export declare const getPath: (source: unknown, path: string) => unknown;
195
-
196
146
  declare interface HeaderAuth {
197
147
  type: "header";
198
148
  env: string;
@@ -208,13 +158,6 @@ declare const HTTP_METHODS: readonly ["GET", "POST", "PUT", "PATCH", "DELETE"];
208
158
 
209
159
  export declare type HttpMethod = (typeof HTTP_METHODS)[number];
210
160
 
211
- export declare interface HttpRequest {
212
- url: string;
213
- method: HttpMethod;
214
- headers: Readonly<Record<string, string>>;
215
- body?: string | FormData | Blob;
216
- }
217
-
218
161
  /** An MCP server reached over Streamable HTTP; the manifest's `auth` signs the requests. */
219
162
  export declare interface HttpUpstream {
220
163
  type: "http";
@@ -240,12 +183,6 @@ export declare const isInteractiveAuth: (auth: AuthSpec) => auth is InteractiveA
240
183
 
241
184
  export declare const isJsonObject: (value: unknown) => value is Record<string, unknown>;
242
185
 
243
- export declare const isMissingFileError: (error: unknown) => boolean;
244
-
245
- export declare const isValidCredentialResponse: (request: CredentialRequest, response: unknown) => response is CredentialResponse;
246
-
247
- export declare const isValidManifest: (value: unknown) => value is Manifest;
248
-
249
186
  export declare interface JsonSchema {
250
187
  type?: "string" | "number" | "integer" | "boolean" | "array" | "object";
251
188
  description?: string;
@@ -272,15 +209,13 @@ export declare interface Manifest {
272
209
  headers?: Readonly<Record<string, string>>;
273
210
  /** OAuth2 entries first, then fallbacks; tried top to bottom, the first that works is used. */
274
211
  auth?: readonly AuthSpec[];
275
- /** Page-wide texts of the credentials page, replacing mcpkit's defaults. */
212
+ /** Page-wide texts of the credentials page, replacing usemcpkit's defaults. */
276
213
  ui?: UiSpec;
277
214
  /** Another MCP server this one fronts: its tools are discovered at runtime, so `tools` stays empty. */
278
215
  upstream?: UpstreamSpec;
279
216
  tools: readonly ToolSpec[];
280
217
  }
281
218
 
282
- export declare const mapResponse: (data: unknown, response?: ResponseSpec) => unknown;
283
-
284
219
  declare type NameList = readonly string[];
285
220
 
286
221
  export declare type NameMapping = Readonly<Record<string, string>>;
@@ -332,8 +267,6 @@ export declare type ParamMap = Readonly<Record<string, Param>>;
332
267
 
333
268
  export declare type ParamOptions = Pick<JsonSchema, "default" | "enum">;
334
269
 
335
- export declare const prepareToolArgs: (tool: ToolSpec, rawArgs?: ToolArgs) => any;
336
-
337
270
  declare interface QueryAuth {
338
271
  type: "query";
339
272
  env: string;
@@ -378,61 +311,21 @@ declare interface RequestSpec {
378
311
  fixedBody?: FixedValues;
379
312
  }
380
313
 
381
- export declare const resolveCliCommand: (action: UiCliAction, domain: string | undefined) => CliTokenCommand;
382
-
383
- export declare interface ResolvedAuth {
384
- headers: Readonly<Record<string, string>>;
385
- query: Readonly<Record<string, string>>;
386
- }
387
-
388
- export declare const resolveHomeDir: (env?: Env) => string;
389
-
390
314
  /** Undefined while the link needs a domain and there is none yet. */
391
315
  export declare const resolveLinkUrl: (url: string, domain: string | undefined) => string | undefined;
392
316
 
393
- /** Builds a fallback entry's auth from its credential values, keyed by env var name. */
394
- export declare const resolveStaticAuth: (auth: FallbackAuth, serverName: string, env: Env) => ResolvedAuth;
395
-
396
317
  export declare interface ResponseSpec {
397
318
  root?: string;
398
319
  fields?: FieldSpec;
399
320
  }
400
321
 
401
- /** The server, and the host of it, a stored secret belongs to. */
402
- export declare interface SecretOwner extends ServerKey {
403
- domain?: string;
404
- }
405
-
406
- /** Where credentials and domains entered in the credentials form are kept, per server and key. */
407
- export declare interface SecretStore {
408
- get: (owner: SecretOwner, key: string) => Promise<string | undefined>;
409
- set: (owner: SecretOwner, key: string, value: string) => Promise<void>;
410
- }
411
-
412
322
  export declare const SERVER_NAME_PATTERN: RegExp;
413
323
 
414
- /** Where a server's settings live in the config: `servers.<category>.<name>`. */
415
- declare type ServerKey = Pick<Manifest, "name" | "category">;
416
-
417
- /** Runs the authorization code + PKCE flow through a loopback redirect and stores the token. */
418
- export declare const signIn: (serverName: string, auth: InteractiveAuth, { context, onAuthorizationUrl }: SignInOptions) => Promise<SignInResult>;
419
-
420
324
  export declare interface SignInCredentialResponse {
421
325
  method: "sign-in";
422
326
  domain?: string;
423
327
  }
424
328
 
425
- declare interface SignInOptions {
426
- context: AuthContext;
427
- /** Receives the URL the user must open to approve access. */
428
- onAuthorizationUrl: (url: string) => void;
429
- }
430
-
431
- export declare interface SignInResult {
432
- token: StoredToken;
433
- tokensFile: string;
434
- }
435
-
436
329
  /** An MCP server started as a child process and spoken to over its stdio. */
437
330
  export declare interface StdioUpstream {
438
331
  type: "stdio";
@@ -452,17 +345,6 @@ export declare interface StdioUpstream {
452
345
  naming?: readonly UpstreamNameRule[];
453
346
  }
454
347
 
455
- declare interface StoredToken {
456
- accessToken: string;
457
- tokenType: string;
458
- refreshToken?: string;
459
- /** Epoch milliseconds; absent when the provider issues non-expiring tokens. */
460
- expiresAt?: number;
461
- scope?: string;
462
- /** Identifies the manifest auth entry that issued the token, so it is refreshed against the same endpoint. */
463
- authKey?: string;
464
- }
465
-
466
348
  export declare const string: (description?: string, options?: ParamOptions) => Param;
467
349
 
468
350
  export declare interface TokenCredentialResponse {
@@ -495,9 +377,6 @@ export declare interface ToolEdition {
495
377
  response?: ResponseSpec;
496
378
  }
497
379
 
498
- export declare class ToolError extends Error {
499
- }
500
-
501
380
  export declare interface ToolSpec {
502
381
  name: string;
503
382
  description: string;
@@ -539,7 +418,7 @@ export declare interface UiLinkAction {
539
418
 
540
419
  /**
541
420
  * What the credentials page shows. On the manifest only `texts` applies (page-wide strings); on an auth entry
542
- * `inputs` (by env var name) and `actions` apply. Anything left out falls back to mcpkit's default text.
421
+ * `inputs` (by env var name) and `actions` apply. Anything left out falls back to usemcpkit's default text.
543
422
  */
544
423
  export declare interface UiSpec {
545
424
  texts?: Partial<UiTexts>;
@@ -548,7 +427,7 @@ export declare interface UiSpec {
548
427
  }
549
428
 
550
429
  /**
551
- * Every string the credentials page shows. `{server}` is filled in by mcpkit; `{key}`, `{name}`, `{label}` and
430
+ * Every string the credentials page shows. `{server}` is filled in by usemcpkit; `{key}`, `{name}`, `{label}` and
552
431
  * `{status}` are filled in where the text is used.
553
432
  */
554
433
  export declare interface UiTexts {
@@ -585,18 +464,7 @@ export declare interface UiTexts {
585
464
  requestFailed: string;
586
465
  }
587
466
 
588
- /** An upstream answered 401: the auth option that produced the credentials is rejected and the next one is tried. */
589
- export declare class UnauthorizedError extends Error {
590
- }
591
-
592
- /** Everything needed to open one upstream connection: where to go, how requests are signed, what the child gets. */
593
- export declare interface UpstreamAccess {
594
- upstream: UpstreamSpec;
595
- headers: Readonly<Record<string, string>>;
596
- env: Readonly<Record<string, string>>;
597
- }
598
-
599
- /** Renames the tools of an upstream server into mcpkit's `<group>:<resource>:<action>` form. */
467
+ /** Renames the tools of an upstream server into usemcpkit's `<group>:<resource>:<action>` form. */
600
468
  export declare interface UpstreamNameRule {
601
469
  /** A regular expression tested against the upstream tool name; the first rule that matches names the tool. */
602
470
  match: string;
@@ -604,7 +472,7 @@ export declare interface UpstreamNameRule {
604
472
  name: string;
605
473
  }
606
474
 
607
- /** A git repository the upstream server is run from, cloned on first use into `~/.mcpkit/repos/<category>/<name>`. */
475
+ /** A git repository the upstream server is run from, cloned on first use into `~/.usemcpkit/repos/<category>/<name>`. */
608
476
  export declare interface UpstreamRepo {
609
477
  url: string;
610
478
  /**
@@ -618,16 +486,4 @@ export declare interface UpstreamRepo {
618
486
 
619
487
  export declare type UpstreamSpec = HttpUpstream | StdioUpstream;
620
488
 
621
- /** The form answer comes over a local HTTP request, so it is checked against what was asked. */
622
- export declare const validateCredentialResponse: (request: CredentialRequest, response: unknown) => string[];
623
-
624
- /** Manifests can be downloaded at runtime, so they are treated as untrusted input. */
625
- export declare const validateManifest: (manifest: unknown) => string[];
626
-
627
- /**
628
- * Runs `run` with the access of an `upstream` manifest. A stdio upstream gets its forwarded credentials, asked for in the credentials form when missing and saved once `run` succeeded; an HTTP one
629
- * tries the manifest's auth options in order like an API call does, moving on when `run` throws UnauthorizedError.
630
- */
631
- export declare const withUpstreamAccess: <T>(manifest: Manifest, run: (access: UpstreamAccess) => Promise<T>, { fetchImpl, timeoutMs, env, ...hooks }?: ExecuteOptions) => Promise<T>;
632
-
633
489
  export { }
@@ -0,0 +1,293 @@
1
+ //#region src/credentials-form/const.ts
2
+ /** HTTP contract between the CLI's loopback credentials form server and the page it serves. */
3
+ var CREDENTIALS_FORM_API = {
4
+ submit: "/api/submit",
5
+ cancel: "/api/cancel",
6
+ import: "/api/import"
7
+ };
8
+ var CREDENTIALS_REQUEST_ELEMENT_ID = "usemcpkit-request";
9
+ /**
10
+ * Functions the CLI's native form window binds into the page: close it, fit it to `{ width, height }`, and open a link
11
+ * in the default browser (a webview has no tabs, so `target="_blank"` links go nowhere).
12
+ */
13
+ var FORM_WINDOW_BINDINGS = {
14
+ close: "usemcpkitCloseWindow",
15
+ fit: "usemcpkitFitWindow",
16
+ openLink: "usemcpkitOpenLink"
17
+ };
18
+ var CREDENTIALS_FORM_SESSION_HEADER = "X-Usemcpkit-Session";
19
+ var WEB_HOST_API_PREFIX = "api.";
20
+ //#endregion
21
+ //#region src/manifest/auth/describe-auth-type.ts
22
+ var describeAuthType = (auth) => auth.type === "oauth" ? "oauth pkce" : auth.type;
23
+ //#endregion
24
+ //#region src/manifest/auth/list-auth-env-names.ts
25
+ var listAuthEnvNames = (auth) => {
26
+ switch (auth.type) {
27
+ case "none": return [];
28
+ case "basic": return [auth.usernameEnv, auth.passwordEnv];
29
+ case "oauth": return auth.clientSecretEnv ? [auth.clientSecretEnv] : [];
30
+ case "bearer":
31
+ case "header":
32
+ case "query": return [auth.env];
33
+ default: return auth;
34
+ }
35
+ };
36
+ //#endregion
37
+ //#region src/manifest/auth/describe-auth-spec.ts
38
+ var describeAuthSpec = (auth) => {
39
+ if (auth.type === "none") return "no auth";
40
+ return [describeAuthType(auth), listAuthEnvNames(auth).join(", ")].filter(Boolean).join(" ");
41
+ };
42
+ //#endregion
43
+ //#region src/manifest/auth/describe-auth.ts
44
+ var describeAuth = (auth) => {
45
+ if (!auth || auth.length === 0) return "no auth";
46
+ return auth.map(describeAuthSpec).join(" → ");
47
+ };
48
+ //#endregion
49
+ //#region src/manifest/auth/is-interactive-auth.ts
50
+ /** OAuth2 auth signs in through the browser and keeps its token in `tokens.json`. */
51
+ var isInteractiveAuth = (auth) => auth.type === "oauth";
52
+ //#endregion
53
+ //#region src/manifest/const.ts
54
+ var SERVER_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;
55
+ /** `resource:action`, for example `pull_request:list`; the action part is optional. */
56
+ var TOOL_NAME_PATTERN = /^[a-z][a-z0-9_]*(:[a-z][a-z0-9_]*)*$/;
57
+ var DOMAIN_PLACEHOLDER = "{domain}";
58
+ /** A host with an optional port and path, for example `ghe.example.com/api/v3`. */
59
+ var DOMAIN_VALUE_PATTERN = /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:\d{1,5})?(\/[a-z0-9._~-]+)*$/i;
60
+ //#endregion
61
+ //#region src/manifest/domain/fill-domain.ts
62
+ var fillDomain = (template, domain) => template.replaceAll(DOMAIN_PLACEHOLDER, domain);
63
+ //#endregion
64
+ //#region src/manifest/domain/apply-auth-domain.ts
65
+ var applyAuthDomain = (auth, domain) => {
66
+ if (auth.type !== "oauth") return auth;
67
+ return {
68
+ ...auth,
69
+ authorizationUrl: fillDomain(auth.authorizationUrl, domain),
70
+ tokenUrl: fillDomain(auth.tokenUrl, domain)
71
+ };
72
+ };
73
+ //#endregion
74
+ //#region src/manifest/domain/apply-tool-edition.ts
75
+ var applyToolEdition = (tool, editionName) => {
76
+ const edition = editionName === void 0 ? void 0 : tool.editions?.[editionName];
77
+ if (!edition) return tool;
78
+ return {
79
+ ...tool,
80
+ request: edition.request,
81
+ response: edition.response ?? tool.response
82
+ };
83
+ };
84
+ //#endregion
85
+ //#region src/manifest/domain/find-edition.ts
86
+ var findEdition = (editions, domain) => {
87
+ const host = (domain.split("/")[0] ?? "").split(":")[0]?.toLowerCase() ?? "";
88
+ return Object.entries(editions ?? {}).find(([, edition]) => edition.hosts.some((suffix) => host.endsWith(suffix.toLowerCase())))?.[0];
89
+ };
90
+ //#endregion
91
+ //#region src/manifest/domain/apply-domain.ts
92
+ /** A copy of the manifest with `{domain}` filled in and each tool set to the domain's edition; without a domain the manifest is returned as is. */
93
+ var applyDomain = (manifest, domain) => {
94
+ if (domain === void 0) return manifest;
95
+ const editionName = findEdition(manifest.editions, domain);
96
+ return {
97
+ ...manifest,
98
+ baseUrl: fillDomain(manifest.baseUrl, domain),
99
+ upstream: manifest.upstream?.type === "http" ? {
100
+ ...manifest.upstream,
101
+ url: fillDomain(manifest.upstream.url, domain)
102
+ } : manifest.upstream,
103
+ auth: manifest.auth?.map((auth) => applyAuthDomain(auth, domain)),
104
+ tools: manifest.tools.map((tool) => applyToolEdition(tool, editionName))
105
+ };
106
+ };
107
+ //#endregion
108
+ //#region src/manifest/domain/is-domain-value.ts
109
+ var isDomainValue = (value) => typeof value === "string" && DOMAIN_VALUE_PATTERN.test(value);
110
+ //#endregion
111
+ //#region src/manifest/is-name-list.ts
112
+ var isNameList = (spec) => Array.isArray(spec);
113
+ //#endregion
114
+ //#region src/manifest/to-name-mapping.ts
115
+ var toNameMapping = (spec) => {
116
+ if (!isNameList(spec)) return spec;
117
+ return Object.fromEntries(spec.map((name) => [name, name]));
118
+ };
119
+ //#endregion
120
+ //#region src/manifest/ui/const.ts
121
+ var DEFAULT_UI_TEXTS = {
122
+ brand: "usemcpkit",
123
+ pageTitle: "usemcpkit · Connect",
124
+ title: "Connect {server}",
125
+ intro: "A tool call needs access to {server}. What you enter is saved in ~/.usemcpkit/config.json and used for later calls.",
126
+ domainLabel: "Domain",
127
+ domainHint: "Host, optionally with a port and path, without https://",
128
+ domainPlaceholder: "api.example.com",
129
+ domainNewHost: "New host, saved with its own credentials.",
130
+ domainShowHosts: "Show saved hosts",
131
+ signInLabel: "Sign in with OAuth2",
132
+ tokenDivider: "or use an access token",
133
+ credentialLegend: "Credential",
134
+ fieldHint: "Or set the {key} environment variable.",
135
+ tokenLabel: "Access token",
136
+ usernameLabel: "Username",
137
+ passwordLabel: "Password",
138
+ headerLabel: "{name} header",
139
+ queryLabel: "{name} query parameter",
140
+ actionsDivider: "or get a token",
141
+ cancel: "Cancel",
142
+ submit: "Save and continue",
143
+ checking: "Checking with {server}…",
144
+ requiredField: "{label} is required",
145
+ savedTitle: "{server} is connected",
146
+ savedBody: "The credentials are saved in ~/.usemcpkit/config.json. This window closes by itself in a few seconds; you can also close it and go back to your MCP client.",
147
+ signingInTitle: "Continue in the new tab",
148
+ signingInBody: "Approve access to {server} in the sign-in tab that just opened. You can close this one.",
149
+ cancelledTitle: "Cancelled",
150
+ cancelledBody: "Nothing was saved. The tool call that asked for credentials fails; calling it again reopens this form.",
151
+ failedTitle: "Something went wrong",
152
+ requestFailed: "the CLI answered {status}"
153
+ };
154
+ var UI_DOMAIN_PLACEHOLDERS = ["domain", "webHost"];
155
+ var UI_PLACEHOLDER_PATTERN = /\{(\w+)\}/g;
156
+ //#endregion
157
+ //#region src/manifest/ui/fill-template.ts
158
+ /** Replaces `{name}` with its value; a placeholder without a value stays as it is. */
159
+ var fillTemplate = (template, values) => template.replace(UI_PLACEHOLDER_PATTERN, (placeholder, name) => values[name] ?? placeholder);
160
+ //#endregion
161
+ //#region src/manifest/ui/read-placeholders.ts
162
+ var readPlaceholders = (template) => Array.from(template.matchAll(UI_PLACEHOLDER_PATTERN), (match) => match[1] ?? "");
163
+ //#endregion
164
+ //#region src/manifest/upstream/name-upstream-tool.ts
165
+ var CATALOG_NAME_PATTERN = /^[a-z][a-z0-9_]*(:[a-z][a-z0-9_]*){2,}$/;
166
+ /**
167
+ * The catalog name `rules` give an upstream tool, from the first rule whose `match` finds the tool name, or undefined
168
+ * when none does. A name that is not `<group>:<resource>:<action>` in lowercase snake case is an error in the
169
+ * manifest, never silently replaced.
170
+ */
171
+ var nameUpstreamTool = (rules, upstreamName) => {
172
+ for (const rule of rules ?? []) {
173
+ const pattern = new RegExp(rule.match);
174
+ if (!pattern.test(upstreamName)) continue;
175
+ const name = upstreamName.replace(pattern, rule.name);
176
+ if (!CATALOG_NAME_PATTERN.test(name)) throw new Error(`naming rule "${rule.match}" turned "${upstreamName}" into "${name}", which is not <group>:<resource>:<action>`);
177
+ return name;
178
+ }
179
+ };
180
+ //#endregion
181
+ //#region src/credentials-form/to-web-host.ts
182
+ /** `api.github.com` → `github.com`, `api.acme.ghe.com` → `acme.ghe.com`, `ghe.example.com/api/v3` → `ghe.example.com`. */
183
+ var toWebHost = (domain) => {
184
+ const [host = domain, ...path] = domain.split("/");
185
+ if (path.length === 0 && host.startsWith("api.")) return host.slice(WEB_HOST_API_PREFIX.length);
186
+ return host;
187
+ };
188
+ //#endregion
189
+ //#region src/credentials-form/resolve-link-url.ts
190
+ /** Undefined while the link needs a domain and there is none yet. */
191
+ var resolveLinkUrl = (url, domain) => {
192
+ if (readPlaceholders(url).some((name) => UI_DOMAIN_PLACEHOLDERS.includes(name)) && !domain) return;
193
+ return fillTemplate(url, {
194
+ domain: domain ?? "",
195
+ webHost: domain ? toWebHost(domain) : ""
196
+ });
197
+ };
198
+ //#endregion
199
+ //#region src/errors/describe-error.ts
200
+ var describeError = (error) => error instanceof Error ? error.message : String(error);
201
+ //#endregion
202
+ //#region src/json/is-json-object.ts
203
+ var isJsonObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
204
+ //#endregion
205
+ //#region src/sdk/define-server.ts
206
+ var defineServer = (manifest) => manifest;
207
+ //#endregion
208
+ //#region src/sdk/define-tool.ts
209
+ var defineTool = (tool) => tool;
210
+ //#endregion
211
+ //#region src/sdk/define-ui.ts
212
+ var defineUI = (ui) => ui;
213
+ //#endregion
214
+ //#region src/sdk/const.ts
215
+ /** Symbol keys are dropped by JSON.stringify, so the marker never reaches a manifest. */
216
+ var OPTIONAL_MARKER = Symbol("optional");
217
+ //#endregion
218
+ //#region src/sdk/is-required-param.ts
219
+ var isRequiredParam = (param) => !param[OPTIONAL_MARKER] && param.default === void 0;
220
+ //#endregion
221
+ //#region src/sdk/strip-optional-marker.ts
222
+ var stripOptionalMarker = (param) => {
223
+ const { [OPTIONAL_MARKER]: _marker, ...rest } = param;
224
+ return rest;
225
+ };
226
+ //#endregion
227
+ //#region src/sdk/input.ts
228
+ /** Builds an object input schema; `required` is derived from the params. */
229
+ var input = (params = {}) => {
230
+ const entries = Object.entries(params);
231
+ const required = entries.filter(([, param]) => isRequiredParam(param)).map(([name]) => name);
232
+ return {
233
+ type: "object",
234
+ properties: Object.fromEntries(entries.map(([name, param]) => [name, stripOptionalMarker(param)])),
235
+ ...required.length > 0 ? { required } : {}
236
+ };
237
+ };
238
+ //#endregion
239
+ //#region src/sdk/optional.ts
240
+ /** Marks a param as not required. Params with a default are optional implicitly. */
241
+ var optional = (param) => {
242
+ return {
243
+ ...param,
244
+ [OPTIONAL_MARKER]: true
245
+ };
246
+ };
247
+ //#endregion
248
+ //#region src/sdk/with-description.ts
249
+ var withDescription = (description) => description ? { description } : {};
250
+ //#endregion
251
+ //#region src/sdk/params/array.ts
252
+ var array = (items, description) => {
253
+ return {
254
+ type: "array",
255
+ items,
256
+ ...withDescription(description)
257
+ };
258
+ };
259
+ //#endregion
260
+ //#region src/sdk/params/boolean.ts
261
+ var boolean = (description, options = {}) => {
262
+ return {
263
+ type: "boolean",
264
+ ...withDescription(description),
265
+ ...options
266
+ };
267
+ };
268
+ //#endregion
269
+ //#region src/sdk/params/number.ts
270
+ var number = (description, options = {}) => {
271
+ return {
272
+ type: "number",
273
+ ...withDescription(description),
274
+ ...options
275
+ };
276
+ };
277
+ //#endregion
278
+ //#region src/sdk/params/string.ts
279
+ var string = (description, options = {}) => {
280
+ return {
281
+ type: "string",
282
+ ...withDescription(description),
283
+ ...options
284
+ };
285
+ };
286
+ //#endregion
287
+ //#region src/sdk/params/one-of.ts
288
+ var oneOf = (values, description, options = {}) => string(description, {
289
+ enum: values,
290
+ ...options
291
+ });
292
+ //#endregion
293
+ export { CREDENTIALS_FORM_API, CREDENTIALS_FORM_SESSION_HEADER, CREDENTIALS_REQUEST_ELEMENT_ID, DEFAULT_UI_TEXTS, FORM_WINDOW_BINDINGS, SERVER_NAME_PATTERN, TOOL_NAME_PATTERN, applyDomain, array, boolean, defineServer, defineTool, defineUI, describeAuth, describeAuthSpec, describeError, fillTemplate, input, isDomainValue, isInteractiveAuth, isJsonObject, listAuthEnvNames, nameUpstreamTool, number, oneOf, optional, resolveLinkUrl, string, toNameMapping };