@jangmanj/mcp-client 0.1.1 → 0.3.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.
@@ -0,0 +1,159 @@
1
+ /**
2
+ * OAuth wiring for the Pi bridge: a file-backed CredentialStore (so sign-ins
3
+ * survive restarts, keyed by issuer per SEP-2352) and a per-server
4
+ * OAuthAuthorization factory wired to the host's consent UI and browser.
5
+ *
6
+ * The library (packages/auth) owns the protocol: discovery, CIMD/DCR, PKCE,
7
+ * iss validation, step-up. This module only connects ports to Pi.
8
+ */
9
+
10
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
11
+ import { dirname } from "node:path";
12
+ import {
13
+ canonicalResource,
14
+ OAuthAuthorization,
15
+ openSystemBrowser,
16
+ SafeFetch,
17
+ startLoopbackRedirect,
18
+ type AuthorizationConsent,
19
+ type ClientRegistration,
20
+ } from "../dist/auth/index.js";
21
+ import type { ResolvedServerConfig } from "./config.ts";
22
+
23
+ export {
24
+ canonicalResource,
25
+ OAuthAuthorization,
26
+ openSystemBrowser,
27
+ startLoopbackRedirect,
28
+ };
29
+ export type { AuthorizationConsent, ClientRegistration };
30
+
31
+ /** JSON-file CredentialStore: write-through, atomic rename, single-process. */
32
+ export class FileCredentialStore {
33
+ readonly #path: string;
34
+ #values: Map<string, string> | undefined;
35
+ #writing: Promise<void> = Promise.resolve();
36
+
37
+ constructor(path: string) {
38
+ this.#path = path;
39
+ }
40
+
41
+ async #load(): Promise<Map<string, string>> {
42
+ if (this.#values) return this.#values;
43
+ try {
44
+ const parsed = JSON.parse(await readFile(this.#path, "utf8"));
45
+ this.#values = new Map(Object.entries(parsed));
46
+ } catch {
47
+ this.#values = new Map();
48
+ }
49
+ return this.#values;
50
+ }
51
+
52
+ async #flush(): Promise<void> {
53
+ const snapshot = JSON.stringify(Object.fromEntries(this.#values ?? new Map()));
54
+ this.#writing = this.#writing.then(async () => {
55
+ await mkdir(dirname(this.#path), { recursive: true });
56
+ const tmp = `${this.#path}.${process.pid}.tmp`;
57
+ await writeFile(tmp, snapshot, { mode: 0o600 });
58
+ await rename(tmp, this.#path);
59
+ });
60
+ return this.#writing;
61
+ }
62
+
63
+ async get(key: string): Promise<string | undefined> {
64
+ return (await this.#load()).get(key);
65
+ }
66
+
67
+ async set(key: string, value: string): Promise<void> {
68
+ (await this.#load()).set(key, value);
69
+ await this.#flush();
70
+ }
71
+
72
+ async delete(key: string): Promise<void> {
73
+ if ((await this.#load()).delete(key)) await this.#flush();
74
+ }
75
+
76
+ /** Delete every entry whose key mentions the resource (logout). */
77
+ async deleteResource(resource: string): Promise<number> {
78
+ const values = await this.#load();
79
+ let n = 0;
80
+ for (const key of [...values.keys()]) {
81
+ if (key.includes(resource)) {
82
+ values.delete(key);
83
+ n++;
84
+ }
85
+ }
86
+ if (n > 0) await this.#flush();
87
+ return n;
88
+ }
89
+ }
90
+
91
+ export interface OAuthProviderOptions {
92
+ readonly config: ResolvedServerConfig;
93
+ readonly store: FileCredentialStore;
94
+ /** Gate: consent prompts proceed only when this returns true (e.g. /mcp login armed). */
95
+ readonly interactive: () => boolean;
96
+ /** Host confirm dialog; when absent all prompts decline. */
97
+ readonly confirm?: (title: string, message: string) => Promise<boolean>;
98
+ readonly browserOpen?: (url: string, signal: AbortSignal) => Promise<void>;
99
+ readonly allowInsecureAuth?: boolean;
100
+ }
101
+
102
+ export interface OAuthProviderHandle {
103
+ readonly provider: OAuthAuthorization;
104
+ readonly closeRedirect: () => void;
105
+ }
106
+
107
+ export async function createOAuthProvider(opts: OAuthProviderOptions): Promise<OAuthProviderHandle> {
108
+ const { config } = opts;
109
+ const redirect = await startLoopbackRedirect("/callback");
110
+ const redirectUri = redirect.redirectUri;
111
+
112
+ const consent: AuthorizationConsent = {
113
+ request: async (prompt, signal) => {
114
+ if (!opts.interactive() || signal.aborted) return { decision: "decline" };
115
+ if (prompt.kind === "client-info") {
116
+ // No CIMD/DCR available: supply a statically configured client, if any.
117
+ const oauth = config.oauth;
118
+ if (oauth?.clientId) {
119
+ const registration: ClientRegistration = {
120
+ clientId: oauth.clientId,
121
+ redirectUris: [redirectUri],
122
+ ...(oauth.clientSecret !== undefined ? { clientSecret: oauth.clientSecret } : {}),
123
+ };
124
+ return { decision: "accept", registration };
125
+ }
126
+ return { decision: "decline" };
127
+ }
128
+ const ok = await (opts.confirm?.(
129
+ `Authorize MCP server "${prompt.serverLabel}"?`,
130
+ `${prompt.issuerHost} will open in your browser to grant access to ${prompt.resource}.` +
131
+ (prompt.scopes.length > 0 ? ` Scopes: ${prompt.scopes.join(" ")}.` : "") +
132
+ (prompt.localhostWarning ? "\nWarning: the authorization server is on localhost." : ""),
133
+ ) ?? Promise.resolve(false));
134
+ if (signal.aborted) return { decision: "cancel" };
135
+ return ok ? { decision: "accept" } : { decision: "decline" };
136
+ },
137
+ };
138
+
139
+ const provider = new OAuthAuthorization({
140
+ resource: config.url as string,
141
+ redirectUri,
142
+ redirect,
143
+ browser: { open: opts.browserOpen ?? openSystemBrowser },
144
+ credentials: opts.store,
145
+ consent,
146
+ serverLabel: config.name,
147
+ dynamicRegistration: { clientName: config.oauth?.clientName ?? "pi" },
148
+ fetch: new SafeFetch({
149
+ allowInsecureDev: opts.allowInsecureAuth ?? false,
150
+ // Insecure-dev mode also permits loopback targets (local dev servers,
151
+ // tests); production keeps SafeFetch's SSRF address blocks.
152
+ ...(opts.allowInsecureAuth
153
+ ? { allowAddress: (hostname: string) => ["127.0.0.1", "localhost", "::1"].includes(hostname) }
154
+ : {}),
155
+ }),
156
+ ...(opts.allowInsecureAuth !== undefined ? { allowInsecureDev: opts.allowInsecureAuth } : {}),
157
+ });
158
+ return { provider, closeRedirect: redirect.close };
159
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Minimal structural types for the Pi extension API surface this bridge uses.
3
+ *
4
+ * This package deliberately does not depend on @earendil-works/pi-coding-agent
5
+ * (see scripts/check-forbidden.mjs): Pi injects its own copies of host packages
6
+ * at runtime, and the factory receives everything through the `pi` argument.
7
+ * The declarations below cover only what the bridge touches. If Pi widens its
8
+ * API, these stay valid; if Pi narrows it, jiti will fail loudly at load.
9
+ */
10
+
11
+ export type PiContent =
12
+ | { type: "text"; text: string }
13
+ | { type: "image"; data: string; mimeType: string };
14
+
15
+ export interface ToolResult {
16
+ content: PiContent[];
17
+ details?: unknown;
18
+ isError?: boolean;
19
+ structuredContent?: unknown;
20
+ }
21
+
22
+ export type ToolExposure = "direct" | "model-only" | "codemode" | "deferred" | "hidden";
23
+
24
+ export interface ToolAnnotations {
25
+ readOnlyHint?: boolean;
26
+ destructiveHint?: boolean;
27
+ idempotentHint?: boolean;
28
+ openWorldHint?: boolean;
29
+ }
30
+
31
+ export interface ToolNamespace {
32
+ name: string;
33
+ aliases?: string[];
34
+ description?: string;
35
+ instructions?: string;
36
+ }
37
+
38
+ export type OnUpdate = (partial: ToolResult) => void;
39
+
40
+ export interface ToolDefinition {
41
+ name: string;
42
+ label: string;
43
+ description: string;
44
+ parameters: Record<string, unknown>;
45
+ exposure?: ToolExposure;
46
+ namespace?: ToolNamespace;
47
+ annotations?: ToolAnnotations;
48
+ promptSnippet?: string;
49
+ execute(
50
+ toolCallId: string,
51
+ params: Record<string, unknown>,
52
+ signal: AbortSignal | undefined,
53
+ onUpdate: OnUpdate | undefined,
54
+ ctx: unknown,
55
+ ): Promise<ToolResult>;
56
+ }
57
+
58
+ /** Shape of one `mcpServers` entry in mcp.json / pi.registerMcpServer(). */
59
+ export interface McpServerEntry {
60
+ type?: string;
61
+ command?: string;
62
+ args?: string[];
63
+ env?: Record<string, string>;
64
+ cwd?: string;
65
+ url?: string;
66
+ headers?: Record<string, string>;
67
+ oauth?: Record<string, unknown>;
68
+ enabled?: boolean;
69
+ exposure?: string;
70
+ toolExposure?: Record<string, string>;
71
+ description?: string;
72
+ timeout?: number;
73
+ }
74
+
75
+ export interface Ui {
76
+ notify(message: string, level?: "info" | "warning" | "error"): void;
77
+ confirm?(title: string, message: string): Promise<boolean>;
78
+ }
79
+
80
+ export interface SessionContext {
81
+ cwd: string;
82
+ hasUI: boolean;
83
+ isProjectTrusted(): boolean;
84
+ ui: Ui;
85
+ }
86
+
87
+ export interface CommandContext {
88
+ ui: Ui;
89
+ }
90
+
91
+ export interface ToolInfo {
92
+ name: string;
93
+ exposure?: string;
94
+ }
95
+
96
+ export interface SystemPromptOptions {
97
+ sections?: Record<string, string>;
98
+ }
99
+
100
+ export interface BeforeAgentStartEvent {
101
+ systemPromptOptions?: SystemPromptOptions;
102
+ }
103
+
104
+ export interface ToolCallEvent {
105
+ toolName: string;
106
+ }
107
+
108
+ export interface McpServersChangeEvent {
109
+ servers: unknown;
110
+ }
111
+
112
+ export interface CommandDefinition {
113
+ description: string;
114
+ handler(args: string, ctx: CommandContext): Promise<void> | void;
115
+ }
116
+
117
+ export interface ExtensionAPI {
118
+ on(event: "session_start", handler: (event: { reason?: string }, ctx: SessionContext) => unknown): void;
119
+ on(event: "session_shutdown", handler: (event: { reason?: string }, ctx: SessionContext) => unknown): void;
120
+ on(event: "before_agent_start", handler: (event: BeforeAgentStartEvent, ctx: SessionContext) => unknown): void;
121
+ on(event: "tool_call", handler: (event: ToolCallEvent, ctx: SessionContext) => unknown): void;
122
+ on(event: "mcp_servers_change", handler: (event: McpServersChangeEvent, ctx: SessionContext) => unknown): void;
123
+ registerTool(definition: ToolDefinition): void;
124
+ registerCommand(name: string, definition: CommandDefinition): void;
125
+ getActiveTools(): string[];
126
+ setActiveTools(names: string[]): void;
127
+ getAllTools(): ToolInfo[];
128
+ getMcpServers(): unknown;
129
+ getSettings?(): Record<string, unknown>;
130
+ }
package/package.json CHANGED
@@ -1,9 +1,20 @@
1
1
  {
2
2
  "name": "@jangmanj/mcp-client",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "MCP 2026-07-28 client library: core, transports, auth, ops, MRTR/cache, OTEL telemetry, and extensions.",
5
5
  "license": "MIT",
6
6
  "author": "JangMan-J",
7
+ "keywords": [
8
+ "mcp",
9
+ "model-context-protocol",
10
+ "pi-package",
11
+ "pi-extension"
12
+ ],
13
+ "pi": {
14
+ "extensions": [
15
+ "./extensions/index.ts"
16
+ ]
17
+ },
7
18
  "repository": {
8
19
  "type": "git",
9
20
  "url": "git+https://github.com/JangMan-J/mcp-client.git"
@@ -19,6 +30,8 @@
19
30
  ],
20
31
  "files": [
21
32
  "dist",
33
+ "extensions",
34
+ "!extensions/test",
22
35
  "README.md",
23
36
  "LICENSE"
24
37
  ],
@@ -70,12 +83,16 @@
70
83
  },
71
84
  "scripts": {
72
85
  "build": "node scripts/build-workspaces.mjs",
73
- "typecheck": "tsc -b tsconfig.json && tsc --noEmit -p tsconfig.test.json",
86
+ "prepare": "npm run build",
87
+ "typecheck": "tsc -b tsconfig.json && tsc --noEmit -p tsconfig.test.json && tsc --noEmit -p tsconfig.extensions.json",
74
88
  "test": "vitest run",
75
89
  "gen:schema": "node scripts/gen-schema-types.mjs",
90
+ "gen:spec-matrix": "node scripts/gen-spec-matrix.mjs",
76
91
  "check:deps": "node scripts/check-deps.mjs",
77
92
  "check:forbidden": "node scripts/check-forbidden.mjs",
78
- "check": "npm run build && npm run typecheck && npm run check:deps && npm run check:forbidden && npm test",
93
+ "check:spec-matrix": "node scripts/gen-spec-matrix.mjs --check",
94
+ "check:spec-drift": "node scripts/check-spec-drift.mjs",
95
+ "check": "npm run build && npm run typecheck && npm run check:deps && npm run check:forbidden && npm run check:spec-matrix && npm test",
79
96
  "smoke:pack": "node scripts/smoke-pack.mjs",
80
97
  "bootstrap:npm": "bash scripts/npm-bootstrap.sh",
81
98
  "prepublishOnly": "npm run check"