@chantier/mcp 0.6.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/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ ## 0.5.0
4
+
5
+ Initial release: `connectServers` (never throws; per-server skip + notice),
6
+ `listTools` pagination, `callTool` with in-band `isError` handling, the
7
+ `mcp__<server>__<tool>` tool adapter, and `loadMcpConfig` merging global
8
+ `~/.chantier/config.json` with project `.mcp.json` including `${VAR}`
9
+ expansion.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ 4. (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 DASHLEA × MLC
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,22 @@
1
+ # @chantier/mcp
2
+
3
+ MCP client for the chantier coding agent: connects Model Context Protocol
4
+ servers (stdio and Streamable HTTP), adapts their tools to chantier's
5
+ `ToolDefinition`, and loads server config from `~/.chantier/config.json`
6
+ (`mcpServers`, `servers`, or a bare name→server record) merged with the
7
+ project `.mcp.json` (Claude Code shape) — with `${VAR}` / `${VAR:-default}`
8
+ expansion.
9
+
10
+ Connecting never throws: a failed server is skipped with a one-line notice.
11
+ Tools surface as `mcp__<server>__<tool>`; `readOnlyHint` annotations map to
12
+ read-only tools; output truncates at 25k chars.
13
+
14
+ ```jsonc
15
+ // .mcp.json (project) or ~/.chantier/config.json
16
+ {
17
+ "mcpServers": {
18
+ "fs": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] },
19
+ "remote": { "type": "http", "url": "https://example.com/mcp", "headers": { "Authorization": "Bearer ${MCP_TOKEN}" } }
20
+ }
21
+ }
22
+ ```
@@ -0,0 +1,261 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ import { CallToolResult, CompatibilityCallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js";
3
+ //#region ../permissions/dist/index.d.mts
4
+ //#region src/engine.d.ts
5
+ type Decision = "allow" | "ask" | "deny";
6
+ interface ApprovalDetail {
7
+ /** Unified diff of the pending mutation, for approval-UI rendering. */
8
+ diff?: string;
9
+ }
10
+ interface PermissionEngine {
11
+ /**
12
+ * Deny → ask → allow, first match wins; allow can never override deny.
13
+ * No rule matched: `readOnly` tools are allowed, mutating tools ask.
14
+ */
15
+ evaluate(toolName: string, specifier?: string, readOnly?: boolean): Decision;
16
+ /** True when a bare-name deny removes the tool from the model's toolset. */
17
+ isRemoved(toolName: string): boolean;
18
+ }
19
+ //#endregion
20
+ //#region ../core/dist/index.d.mts
21
+ //#region src/todo.d.ts
22
+ /**
23
+ * Frozen v0.6.0 contract (spec /home/debian/portfolio/chantier/v06-spec.md
24
+ * §Frozen contract): the todo-checklist step shape shared by the core tool,
25
+ * the store, and the TUI. Types only — Worker CoreExt implements the tool;
26
+ * the TUI worker implements the store fields and rendering.
27
+ */
28
+ /** One checklist row. Whole-list replace per call; at most one in_progress. */
29
+ interface TodoStep {
30
+ readonly content: string;
31
+ readonly status: "pending" | "in_progress" | "completed";
32
+ }
33
+ //#endregion
34
+ //#region src/types.d.ts
35
+ interface TextBlock {
36
+ type: "text";
37
+ text: string;
38
+ }
39
+ interface ToolCallBlock {
40
+ type: "tool-call";
41
+ id: string;
42
+ name: string;
43
+ args: Record<string, unknown>;
44
+ }
45
+ interface Usage {
46
+ inputTokens: number;
47
+ outputTokens: number;
48
+ }
49
+ interface SystemMessage {
50
+ role: "system";
51
+ content: string;
52
+ }
53
+ interface UserMessage {
54
+ role: "user";
55
+ content: Array<TextBlock>;
56
+ }
57
+ interface AssistantMessage {
58
+ role: "assistant";
59
+ content: Array<TextBlock | ToolCallBlock>;
60
+ usage?: Usage;
61
+ }
62
+ interface ToolResultMessage {
63
+ role: "tool-result";
64
+ toolCallId: string;
65
+ toolName: string;
66
+ content: string;
67
+ }
68
+ type Message = SystemMessage | UserMessage | AssistantMessage | ToolResultMessage;
69
+ /**
70
+ * Marker appended to the JSONL when a compaction replaces the older part of the
71
+ * conversation with a summary. The log stays append-only: nothing is rewritten
72
+ * or deleted, `load()` always returns everything (TUI/rewind keep working), and
73
+ * `view()` folds compaction entries into the model-facing context.
74
+ *
75
+ * `firstKeptMessageIndex` is the 0-based ordinal of the first `message` entry
76
+ * that is kept verbatim after this compaction (the session header and
77
+ * compaction entries themselves are not counted). Ordinals are stable because
78
+ * the log is append-only — entries are never reordered, rewritten, or removed —
79
+ * so no entry ids are needed, and `--continue`/fork of an old file stays safe.
80
+ *
81
+ * Convention: the compaction entry is immediately followed by a regular `user`
82
+ * message entry carrying the summary text prefixed with COMPACTED_MARKER. The
83
+ * summary message is a real log entry (its ordinal is always >=
84
+ * firstKeptMessageIndex), so `view()` returns it naturally and resume flows
85
+ * stay plain `Message[]` with no synthetic messages.
86
+ */
87
+ interface CompactionEntry {
88
+ type: "compaction";
89
+ summary: string;
90
+ firstKeptMessageIndex: number;
91
+ tokensBefore: number;
92
+ createdAt: string;
93
+ }
94
+ interface ToolContext {
95
+ cwd: string;
96
+ session: SessionStore;
97
+ permission: PermissionEngine;
98
+ signal: AbortSignal;
99
+ /**
100
+ * v0.6: live todo-trail hook. The todo tool forwards each accepted
101
+ * checklist to it; the interactive loop binds it to the TUI store.
102
+ * Undefined = the checklist is accepted without a live consumer.
103
+ */
104
+ onTodo?: (steps: readonly TodoStep[]) => void;
105
+ }
106
+ interface ToolDefinition {
107
+ name: string;
108
+ description: string;
109
+ inputSchema: {
110
+ type: "object";
111
+ properties: Record<string, unknown>;
112
+ required?: string[];
113
+ };
114
+ readOnly: boolean;
115
+ handler: (input: Record<string, unknown>, ctx: ToolContext) => Promise<string>;
116
+ /** How to extract the permission specifier (e.g. path, command) from input. */
117
+ specifier?: (input: Record<string, unknown>) => string | undefined;
118
+ /**
119
+ * Optional approval-UI metadata (e.g. a unified diff preview of the pending
120
+ * mutation), passed to the sink via ApprovalRequest.detail. Shape: ApprovalDetail
121
+ * from @chantier/permissions. Called with the same input the handler will
122
+ * receive; a returned undefined simply omits the metadata. May be async
123
+ * (e.g. reading the file to build a diff). Sinks that ignore detail are unaffected.
124
+ */
125
+ askDetail?: (input: Record<string, unknown>, ctx: ToolContext) => ApprovalDetail | undefined | Promise<ApprovalDetail | undefined>;
126
+ }
127
+ type SessionHeader = {
128
+ type: "session";
129
+ id: string;
130
+ cwd: string;
131
+ provider: string;
132
+ model: string;
133
+ createdAt: string;
134
+ };
135
+ type SessionEntry = SessionHeader | {
136
+ type: "message";
137
+ message: Message;
138
+ } | CompactionEntry;
139
+ /**
140
+ * `view` folds the append-only log into the model-facing context: the summary
141
+ * message convention replaces everything before the last compaction's
142
+ * `firstKeptMessageIndex`. Optional so lightweight fakes (tests) remain valid;
143
+ * real stores from this module always implement it, and
144
+ * `sessionView(store.load(id))` is the equivalent free-function form.
145
+ */
146
+ interface SessionStore {
147
+ id: string;
148
+ dir: string;
149
+ append(entry: SessionEntry): Promise<void>;
150
+ load(id: string): Promise<SessionEntry[]>;
151
+ view?(id: string): Promise<Message[]>;
152
+ }
153
+ //#endregion
154
+ //#region src/adapter.d.ts
155
+ /**
156
+ * What `client.callTool` resolves to: a normal result (content blocks) or a
157
+ * task/compatibility result (opaque `toolResult`, rendered as no content).
158
+ */
159
+ type ToolResultPayload = CallToolResult | CompatibilityCallToolResult;
160
+ /**
161
+ * A connected MCP server (or any object exposing the same surface — tests
162
+ * use stand-ins). The tool adapter and the connection loop share this ref.
163
+ */
164
+ interface McpServerRef {
165
+ readonly name: string;
166
+ readonly client: Client;
167
+ }
168
+ /** Model-facing tool output is capped at this many chars, with a visible note. */
169
+ export declare const MAX_MCP_OUTPUT_CHARS = 25000;
170
+ /** Per-call SDK request timeout; a dead server surfaces as a failed tool result. */
171
+ export declare const MCP_CALL_TIMEOUT_MS = 60000;
172
+ export declare function sanitizeMcpName(raw: string): string;
173
+ /** Adapter tool name: `mcp__<server>__<tool>` with sanitized segments. */
174
+ export declare function mcpToolName(server: string, tool: string): string;
175
+ /**
176
+ * Adapts one server tool to a chantier ToolDefinition. A string return is a
177
+ * skip reason (the tool does not fit chantier's object-schema shape); the
178
+ * caller turns it into a notice.
179
+ */
180
+ export declare function toToolDefinition(server: McpServerRef, info: Tool): ToolDefinition | string;
181
+ /** One tool call against the server; `timeout` defaults to MCP_CALL_TIMEOUT_MS. */
182
+ export declare function callTool(server: McpServerRef, name: string, args: Record<string, unknown>, opts?: {
183
+ timeout?: number;
184
+ signal?: AbortSignal;
185
+ }): Promise<ToolResultPayload>;
186
+ /**
187
+ * Renders a tool result in-band: text blocks joined by newlines. An
188
+ * `isError` result still returns its text (the model reads the failure);
189
+ * transport-level throws are NOT caught here — the engine turns them into
190
+ * failed tool results.
191
+ */
192
+ export declare function renderToolContent(result: ToolResultPayload): string;
193
+ export declare function truncateMcpOutput(text: string, maxChars?: number): string;
194
+ //#endregion
195
+ //#region src/client.d.ts
196
+ /** One server entry from config (stdio, http; sse/ws are recognized but unsupported). */
197
+ interface McpServerConfig {
198
+ /** stdio: executable to spawn. */
199
+ command?: string;
200
+ args?: readonly string[];
201
+ /** stdio: extra env merged over the parent process env. */
202
+ env?: Readonly<Record<string, string>>;
203
+ /** http: endpoint URL. */
204
+ url?: string;
205
+ /** "http" (supported), "stdio" (implied by `command`), "sse"/"ws" (skipped with a notice). */
206
+ type?: string;
207
+ headers?: Readonly<Record<string, string>>;
208
+ }
209
+ interface McpConnection extends McpServerRef {
210
+ /** Adapted tools ready to merge into the agent toolset. */
211
+ readonly tools: readonly ToolDefinition[];
212
+ }
213
+ interface McpConnectOptions {
214
+ /** Spawn cwd for stdio servers; defaults to the process cwd. */
215
+ readonly cwd?: string;
216
+ }
217
+ interface McpConnectResult {
218
+ readonly connections: readonly McpConnection[];
219
+ /** One-line diagnostics: skipped servers, unsupported transports, dead spawns. */
220
+ readonly notices: readonly string[];
221
+ }
222
+ /**
223
+ * Connects every configured server. NEVER throws: a per-server failure is a
224
+ * skip plus a notice, so one dead server cannot take the session down.
225
+ */
226
+ export declare function connectServers(servers: Readonly<Record<string, McpServerConfig>>, opts?: McpConnectOptions): Promise<McpConnectResult>;
227
+ /** Lists a connection's tools, following `nextCursor` pagination to the end. */
228
+ export declare function listTools(server: McpServerRef): Promise<Tool[]>;
229
+ /** Closes every connection; an already-dead server must not block shutdown. */
230
+ export declare function closeAll(connections: readonly McpServerRef[]): Promise<void>;
231
+ //#endregion
232
+ //#region src/config.d.ts
233
+ interface McpConfigOptions {
234
+ /** Project root holding `.mcp.json`; defaults to the process cwd. */
235
+ readonly cwd?: string;
236
+ }
237
+ interface McpConfigResult {
238
+ readonly servers: Readonly<Record<string, McpServerConfig>>;
239
+ /** Servers from the project .mcp.json — trust-gated before connecting. */
240
+ readonly projectServers: Readonly<Record<string, McpServerConfig>>;
241
+ /** Servers from the user's ~/.chantier/config.json — never gated. */
242
+ readonly globalServers: Readonly<Record<string, McpServerConfig>>;
243
+ readonly notices: readonly string[];
244
+ }
245
+ /**
246
+ * Merges the global `~/.chantier/config.json` server map (accepting the
247
+ * `{"mcpServers": …}`, `{"servers": …}`, and bare name→server spellings)
248
+ * with the project `.mcp.json` (Claude Code shape: top-level `mcpServers`).
249
+ * Project entries win on name collisions. `${VAR}` / `${VAR:-default}`
250
+ * expansion applies to every string field; missing files contribute nothing.
251
+ */
252
+ export declare function loadMcpConfig(opts?: McpConfigOptions): Promise<McpConfigResult>;
253
+ //#endregion
254
+ //#region src/guard.d.ts
255
+ /**
256
+ * The package's canonical object guard (no shared type-guard module exists
257
+ * in this package; keep exactly one definition here and import it).
258
+ */
259
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
260
+ //#endregion
261
+ export type { McpConfigOptions, McpConfigResult, McpConnectOptions, McpConnectResult, McpConnection, McpServerConfig, McpServerRef };
package/dist/index.mjs ADDED
@@ -0,0 +1,298 @@
1
+ import process from "node:process";
2
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
4
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
5
+ import { readFile } from "node:fs/promises";
6
+ import { homedir } from "node:os";
7
+ import path from "node:path";
8
+ import { z } from "zod";
9
+ //#region src/guard.ts
10
+ /**
11
+ * The package's canonical object guard (no shared type-guard module exists
12
+ * in this package; keep exactly one definition here and import it).
13
+ */
14
+ function isRecord(value) {
15
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16
+ }
17
+ //#endregion
18
+ //#region src/adapter.ts
19
+ /** Model-facing tool output is capped at this many chars, with a visible note. */
20
+ const MAX_MCP_OUTPUT_CHARS = 25e3;
21
+ /** Per-call SDK request timeout; a dead server surfaces as a failed tool result. */
22
+ const MCP_CALL_TIMEOUT_MS = 6e4;
23
+ /** Non-`[A-Za-z0-9_-]` characters collapse to `_` (Claude Code / RULE_PATTERN charset). */
24
+ const UNSAFE_NAME_CHARS = /[^A-Za-z0-9_-]/g;
25
+ function sanitizeMcpName(raw) {
26
+ const cleaned = raw.replace(UNSAFE_NAME_CHARS, "_");
27
+ return cleaned.length === 0 ? "_" : cleaned;
28
+ }
29
+ /** Adapter tool name: `mcp__<server>__<tool>` with sanitized segments. */
30
+ function mcpToolName(server, tool) {
31
+ return `mcp__${sanitizeMcpName(server)}__${sanitizeMcpName(tool)}`;
32
+ }
33
+ /**
34
+ * Adapts one server tool to a chantier ToolDefinition. A string return is a
35
+ * skip reason (the tool does not fit chantier's object-schema shape); the
36
+ * caller turns it into a notice.
37
+ */
38
+ function toToolDefinition(server, info) {
39
+ const schema = info.inputSchema;
40
+ if (typeof schema !== "object" || schema === null) return "inputSchema is not an object";
41
+ if (!("type" in schema) || schema.type !== "object") return "inputSchema type is not \"object\"";
42
+ const properties = "properties" in schema && isRecord(schema.properties) ? schema.properties : {};
43
+ const requiredList = "required" in schema && Array.isArray(schema.required) && schema.required.every((entry) => typeof entry === "string") ? schema.required : void 0;
44
+ const originalName = info.name;
45
+ return {
46
+ name: mcpToolName(server.name, originalName),
47
+ description: info.description ?? "",
48
+ inputSchema: {
49
+ type: "object",
50
+ properties,
51
+ ...requiredList === void 0 ? {} : { required: [...requiredList] }
52
+ },
53
+ readOnly: info.annotations?.readOnlyHint === true,
54
+ handler: async (input, ctx) => {
55
+ return truncateMcpOutput(renderToolContent(await callTool(server, originalName, input, { signal: ctx.signal })));
56
+ }
57
+ };
58
+ }
59
+ /** One tool call against the server; `timeout` defaults to MCP_CALL_TIMEOUT_MS. */
60
+ async function callTool(server, name, args, opts = {}) {
61
+ return server.client.callTool({
62
+ name,
63
+ arguments: args
64
+ }, void 0, {
65
+ timeout: opts.timeout ?? 6e4,
66
+ ...opts.signal === void 0 ? {} : { signal: opts.signal }
67
+ });
68
+ }
69
+ /**
70
+ * Renders a tool result in-band: text blocks joined by newlines. An
71
+ * `isError` result still returns its text (the model reads the failure);
72
+ * transport-level throws are NOT caught here — the engine turns them into
73
+ * failed tool results.
74
+ */
75
+ function renderToolContent(result) {
76
+ if ("toolResult" in result) return "(no content)";
77
+ const parts = [];
78
+ for (const block of result.content) if (block.type === "text") parts.push(block.text);
79
+ if (parts.length > 0) return parts.join("\n");
80
+ if (result.isError === true) return "mcp tool failed (no error details returned)";
81
+ return "(no content)";
82
+ }
83
+ function truncateMcpOutput(text, maxChars = MAX_MCP_OUTPUT_CHARS) {
84
+ if (text.length <= maxChars) return text;
85
+ return `${text.slice(0, maxChars)}\n[truncated: showing first ${maxChars} of ${text.length} chars]`;
86
+ }
87
+ //#endregion
88
+ //#region src/client.ts
89
+ /** Client identity advertised during MCP initialization. */
90
+ const CLIENT_INFO = {
91
+ name: "chantier",
92
+ version: "0.5.0"
93
+ };
94
+ /**
95
+ * Connects every configured server. NEVER throws: a per-server failure is a
96
+ * skip plus a notice, so one dead server cannot take the session down.
97
+ */
98
+ async function connectServers(servers, opts = {}) {
99
+ const connections = [];
100
+ const notices = [];
101
+ for (const [name, config] of Object.entries(servers)) {
102
+ if (config.type === "sse" || config.type === "ws") {
103
+ notices.push(`server '${name}' skipped: ${config.type} transport not supported in 0.6 (use type "http")`);
104
+ continue;
105
+ }
106
+ let client;
107
+ try {
108
+ const transport = createTransport(name, config, opts.cwd);
109
+ client = new Client(CLIENT_INFO);
110
+ await client.connect(transport);
111
+ const tools = await collectTools({
112
+ name,
113
+ client
114
+ }, notices);
115
+ connections.push({
116
+ name,
117
+ client,
118
+ tools
119
+ });
120
+ client = void 0;
121
+ } catch (error) {
122
+ await client?.close().catch(() => void 0);
123
+ notices.push(`server '${name}' skipped: ${error.message}`);
124
+ }
125
+ }
126
+ return {
127
+ connections,
128
+ notices
129
+ };
130
+ }
131
+ function createTransport(_name, config, cwd) {
132
+ if (typeof config.command === "string" && config.command.length > 0) {
133
+ const env = {};
134
+ for (const [key, value] of Object.entries(process.env)) if (value !== void 0) env[key] = value;
135
+ Object.assign(env, config.env);
136
+ return new StdioClientTransport({
137
+ command: config.command,
138
+ args: [...config.args ?? []],
139
+ env,
140
+ stderr: "pipe",
141
+ ...cwd === void 0 ? {} : { cwd }
142
+ });
143
+ }
144
+ if (typeof config.url === "string" && config.url.length > 0) return new StreamableHTTPClientTransport(new URL(config.url), { requestInit: { headers: { ...config.headers } } });
145
+ throw new Error("config has neither a `command` (stdio) nor a `url` (http)");
146
+ }
147
+ async function collectTools(server, notices) {
148
+ const tools = [];
149
+ for (const info of await listAllTools(server.client)) {
150
+ const adapted = toToolDefinition(server, info);
151
+ if (typeof adapted === "string") {
152
+ notices.push(`server '${server.name}' tool '${info.name}' skipped: ${adapted}`);
153
+ continue;
154
+ }
155
+ tools.push(adapted);
156
+ }
157
+ return tools;
158
+ }
159
+ /** Lists a connection's tools, following `nextCursor` pagination to the end. */
160
+ async function listTools(server) {
161
+ return listAllTools(server.client);
162
+ }
163
+ async function listAllTools(client) {
164
+ const all = [];
165
+ let cursor;
166
+ for (;;) {
167
+ const page = await client.listTools(cursor === void 0 ? void 0 : { cursor });
168
+ all.push(...page.tools);
169
+ const next = page.nextCursor;
170
+ if (next === void 0) break;
171
+ cursor = next;
172
+ }
173
+ return all;
174
+ }
175
+ /** Closes every connection; an already-dead server must not block shutdown. */
176
+ async function closeAll(connections) {
177
+ for (const conn of connections) try {
178
+ await conn.client.close();
179
+ } catch {}
180
+ }
181
+ //#endregion
182
+ //#region src/config.ts
183
+ const ServerConfigSchema = z.object({
184
+ command: z.string().min(1).optional(),
185
+ args: z.array(z.string()).optional(),
186
+ env: z.record(z.string(), z.string()).optional(),
187
+ url: z.string().min(1).optional(),
188
+ type: z.string().optional(),
189
+ headers: z.record(z.string(), z.string()).optional()
190
+ }).refine((config) => config.command !== void 0 || config.url !== void 0, { message: "needs a `command` (stdio) or a `url` (http)" });
191
+ /**
192
+ * Merges the global `~/.chantier/config.json` server map (accepting the
193
+ * `{"mcpServers": …}`, `{"servers": …}`, and bare name→server spellings)
194
+ * with the project `.mcp.json` (Claude Code shape: top-level `mcpServers`).
195
+ * Project entries win on name collisions. `${VAR}` / `${VAR:-default}`
196
+ * expansion applies to every string field; missing files contribute nothing.
197
+ */
198
+ async function loadMcpConfig(opts = {}) {
199
+ const notices = [];
200
+ const globalServers = await readGlobalServers(notices);
201
+ const projectServers = await readProjectServers(opts.cwd ?? process.cwd(), notices);
202
+ const servers = {
203
+ ...globalServers,
204
+ ...projectServers
205
+ };
206
+ for (const name of Object.keys(projectServers)) if (name in globalServers) notices.push(`server '${name}' defined in global and project config; project wins`);
207
+ return {
208
+ servers,
209
+ projectServers,
210
+ globalServers,
211
+ notices
212
+ };
213
+ }
214
+ async function readGlobalServers(notices) {
215
+ const file = path.join(homedir(), ".chantier", "config.json");
216
+ const raw = await readJsonObject(file, notices);
217
+ if (raw === void 0) return {};
218
+ if (isRecord(raw.mcpServers)) return parseServerMap(file, raw.mcpServers, notices);
219
+ if (isRecord(raw.servers)) return parseServerMap(file, raw.servers, notices);
220
+ const entries = Object.entries(raw);
221
+ if (entries.length > 0 && entries.every(([, value]) => ServerConfigSchema.safeParse(value).success)) return parseServerMap(file, raw, notices);
222
+ return {};
223
+ }
224
+ async function readProjectServers(cwd, notices) {
225
+ const file = path.join(cwd, ".mcp.json");
226
+ const raw = await readJsonObject(file, notices);
227
+ if (raw === void 0) return {};
228
+ if (!isRecord(raw.mcpServers)) {
229
+ notices.push(`${file}: no mcpServers key, skipped`);
230
+ return {};
231
+ }
232
+ return parseServerMap(file, raw.mcpServers, notices);
233
+ }
234
+ function parseServerMap(file, raw, notices) {
235
+ if (!isRecord(raw)) {
236
+ notices.push(`${file}: mcpServers must be an object, skipped`);
237
+ return {};
238
+ }
239
+ const out = {};
240
+ for (const [name, value] of Object.entries(raw)) {
241
+ const checked = ServerConfigSchema.safeParse(value);
242
+ if (!checked.success) {
243
+ const issue = checked.error.issues[0];
244
+ notices.push(`${file}: server '${name}' skipped: ${issue === void 0 ? "not a server config" : `${issue.path.join(".") || "config"} ${issue.message}`}`);
245
+ continue;
246
+ }
247
+ out[name] = expandServer(checked.data);
248
+ }
249
+ return out;
250
+ }
251
+ async function readJsonObject(file, notices) {
252
+ let text;
253
+ try {
254
+ text = await readFile(file, "utf8");
255
+ } catch {
256
+ return;
257
+ }
258
+ let parsed;
259
+ try {
260
+ parsed = JSON.parse(text);
261
+ } catch (error) {
262
+ notices.push(`${file}: invalid JSON, skipped (${error.message})`);
263
+ return;
264
+ }
265
+ if (!isRecord(parsed)) {
266
+ notices.push(`${file}: expected a JSON object, skipped`);
267
+ return;
268
+ }
269
+ return parsed;
270
+ }
271
+ /** POSIX-ish `${VAR}` → env (unset becomes "") and `${VAR:-default}` → env or default. */
272
+ const VAR_PATTERN = /\$\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\}/g;
273
+ function expandString(raw) {
274
+ return raw.replace(VAR_PATTERN, (_match, name, _group, fallback) => {
275
+ const value = process.env[name];
276
+ return value === void 0 || value.length === 0 ? fallback ?? "" : value;
277
+ });
278
+ }
279
+ function expandServer(config) {
280
+ const out = {};
281
+ if (config.command !== void 0) out.command = expandString(config.command);
282
+ if (config.args !== void 0) out.args = config.args.map((entry) => expandString(entry));
283
+ if (config.env !== void 0) {
284
+ const env = {};
285
+ for (const [key, value] of Object.entries(config.env)) env[key] = expandString(value);
286
+ out.env = env;
287
+ }
288
+ if (config.url !== void 0) out.url = expandString(config.url);
289
+ if (config.type !== void 0) out.type = expandString(config.type);
290
+ if (config.headers !== void 0) {
291
+ const headers = {};
292
+ for (const [key, value] of Object.entries(config.headers)) headers[key] = expandString(value);
293
+ out.headers = headers;
294
+ }
295
+ return out;
296
+ }
297
+ //#endregion
298
+ export { MAX_MCP_OUTPUT_CHARS, MCP_CALL_TIMEOUT_MS, callTool, closeAll, connectServers, isRecord, listTools, loadMcpConfig, mcpToolName, renderToolContent, sanitizeMcpName, toToolDefinition, truncateMcpOutput };
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@chantier/mcp",
3
+ "version": "0.6.0",
4
+ "type": "module",
5
+ "license": "Apache-2.0",
6
+ "description": "MCP client: server connections, tool adapters, and config loading for the chantier coding agent",
7
+ "exports": {
8
+ ".": {
9
+ "development": "./src/index.ts",
10
+ "types": "./dist/index.d.mts",
11
+ "import": "./dist/index.mjs"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "LICENSE",
18
+ "CHANGELOG.md"
19
+ ],
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/mlcassociation/chantier.git"
26
+ },
27
+ "homepage": "https://github.com/mlcassociation/chantier#readme",
28
+ "bugs": {
29
+ "url": "https://github.com/mlcassociation/chantier/issues"
30
+ },
31
+ "engines": {
32
+ "node": ">=22"
33
+ },
34
+ "scripts": {
35
+ "build": "tsdown src/index.ts --format esm --dts --clean --out-dir dist",
36
+ "prepublishOnly": "npm run build"
37
+ },
38
+ "dependencies": {
39
+ "@modelcontextprotocol/sdk": "^1.30.0",
40
+ "zod": "^3.25.0"
41
+ },
42
+ "devDependencies": {
43
+ "tsdown": "0.23.0"
44
+ }
45
+ }