clanka 0.11.0 → 0.12.1
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 +49 -0
- package/dist/Acp.d.ts +1 -1
- package/dist/Acp.d.ts.map +1 -1
- package/dist/Acp.js +122 -7
- package/dist/Acp.js.map +1 -1
- package/dist/Acp.test.js +240 -0
- package/dist/Acp.test.js.map +1 -1
- package/dist/Agent.d.ts.map +1 -1
- package/dist/Agent.js +26 -8
- package/dist/Agent.js.map +1 -1
- package/dist/AgentExecutor.js +15 -1
- package/dist/AgentExecutor.js.map +1 -1
- package/dist/AgentTools.d.ts +7 -0
- package/dist/AgentTools.d.ts.map +1 -1
- package/dist/AgentTools.js +7 -0
- package/dist/AgentTools.js.map +1 -1
- package/dist/McpConfig.d.ts +36 -0
- package/dist/McpConfig.d.ts.map +1 -0
- package/dist/McpConfig.js +182 -0
- package/dist/McpConfig.js.map +1 -0
- package/dist/McpConfig.test.d.ts +2 -0
- package/dist/McpConfig.test.d.ts.map +1 -0
- package/dist/McpConfig.test.js +163 -0
- package/dist/McpConfig.test.js.map +1 -0
- package/dist/McpServers.d.ts +176 -0
- package/dist/McpServers.d.ts.map +1 -0
- package/dist/McpServers.js +707 -0
- package/dist/McpServers.js.map +1 -0
- package/dist/McpServers.test.d.ts +2 -0
- package/dist/McpServers.test.d.ts.map +1 -0
- package/dist/McpServers.test.js +717 -0
- package/dist/McpServers.test.js.map +1 -0
- package/dist/TypeBuilder.d.ts +9 -0
- package/dist/TypeBuilder.d.ts.map +1 -1
- package/dist/TypeBuilder.js +24 -11
- package/dist/TypeBuilder.js.map +1 -1
- package/dist/TypeBuilder.test.js +33 -0
- package/dist/TypeBuilder.test.js.map +1 -1
- package/dist/bin/{Effect-zUBunSAW.mjs → Effect-DuThyCJ1.mjs} +87 -9
- package/dist/bin/Effect-DuThyCJ1.mjs.map +1 -0
- package/dist/bin/McpClient-CIiPyMDJ.mjs +36 -0
- package/dist/bin/McpClient-CIiPyMDJ.mjs.map +1 -0
- package/dist/bin/{OutputFormatter-BPdc6RmH.mjs → OutputFormatter-BvIjvUmT.mjs} +3 -3
- package/dist/bin/{OutputFormatter-BPdc6RmH.mjs.map → OutputFormatter-BvIjvUmT.mjs.map} +1 -1
- package/dist/bin/{Schema-C2Y2y3tU.mjs → Schema-DcXUXpRg.mjs} +831 -35
- package/dist/bin/Schema-DcXUXpRg.mjs.map +1 -0
- package/dist/bin/{SemanticSearch-BKZxP19F.mjs → SemanticSearch-CdGA4CIC.mjs} +5 -5
- package/dist/bin/{SemanticSearch-BKZxP19F.mjs.map → SemanticSearch-CdGA4CIC.mjs.map} +1 -1
- package/dist/bin/{Stream-BvmRbTMu.mjs → Stream-I9SRMlLj.mjs} +20 -22
- package/dist/bin/Stream-I9SRMlLj.mjs.map +1 -0
- package/dist/bin/cli.mjs +17646 -802
- package/dist/bin/cli.mjs.map +1 -1
- package/dist/bin/{index.min-DbZbUHX3.mjs → index.min-Bkz7vIWv.mjs} +5 -5
- package/dist/bin/{index.min-DbZbUHX3.mjs.map → index.min-Bkz7vIWv.mjs.map} +1 -1
- package/dist/bin/rolldown-runtime-zY4HT0JA.mjs +30 -0
- package/dist/bin/{turndown.cjs-DK29wZw3.mjs → turndown.cjs-LntFxFyd.mjs} +2 -2
- package/dist/bin/{turndown.cjs-DK29wZw3.mjs.map → turndown.cjs-LntFxFyd.mjs.map} +1 -1
- package/dist/cli.js +24 -2
- package/dist/cli.js.map +1 -1
- package/dist/fixtures/McpFakeServer.d.ts +47 -0
- package/dist/fixtures/McpFakeServer.d.ts.map +1 -0
- package/dist/fixtures/McpFakeServer.js +112 -0
- package/dist/fixtures/McpFakeServer.js.map +1 -0
- package/dist/fixtures/McpStdioServer.d.ts +2 -0
- package/dist/fixtures/McpStdioServer.d.ts.map +1 -0
- package/dist/fixtures/McpStdioServer.js +53 -0
- package/dist/fixtures/McpStdioServer.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/Acp.test.ts +348 -0
- package/src/Acp.ts +154 -5
- package/src/Agent.ts +38 -10
- package/src/AgentExecutor.ts +14 -1
- package/src/AgentTools.ts +8 -0
- package/src/McpConfig.test.ts +238 -0
- package/src/McpConfig.ts +255 -0
- package/src/McpServers.test.ts +1050 -0
- package/src/McpServers.ts +1072 -0
- package/src/TypeBuilder.test.ts +70 -0
- package/src/TypeBuilder.ts +41 -14
- package/src/cli.ts +46 -0
- package/src/fixtures/McpFakeServer.ts +162 -0
- package/src/fixtures/McpStdioServer.ts +60 -0
- package/src/index.ts +5 -0
- package/dist/bin/Effect-zUBunSAW.mjs.map +0 -1
- package/dist/bin/McpClient-CnP2P7c9.mjs +0 -14179
- package/dist/bin/McpClient-CnP2P7c9.mjs.map +0 -1
- package/dist/bin/Schema-C2Y2y3tU.mjs.map +0 -1
- package/dist/bin/Stream-BvmRbTMu.mjs.map +0 -1
package/src/Agent.ts
CHANGED
|
@@ -5,6 +5,7 @@ import * as Model from "effect/ai/Model"
|
|
|
5
5
|
import type * as Response from "effect/ai/Response"
|
|
6
6
|
import * as AgentExecutor from "./AgentExecutor.ts"
|
|
7
7
|
import * as AgentSkills from "./AgentSkills.ts"
|
|
8
|
+
import * as McpServers from "./McpServers.ts"
|
|
8
9
|
import { ToolkitRenderer } from "./ToolkitRenderer.ts"
|
|
9
10
|
import { stripWrappingCodeFence } from "./ScriptExtraction.ts"
|
|
10
11
|
import type * as Path from "effect/Path"
|
|
@@ -204,21 +205,25 @@ export const makeWith = Effect.fnUntraced(function* <
|
|
|
204
205
|
|
|
205
206
|
const singleTool = yield* SingleTools.pipe(Effect.provide(SingleToolHandlers))
|
|
206
207
|
const capabilities = yield* executor.capabilities
|
|
208
|
+
// Shared with every sub-agent, so they use the same connections.
|
|
209
|
+
const mcpServers = Option.getOrUndefined(
|
|
210
|
+
yield* Effect.serviceOption(McpServers.McpServers),
|
|
211
|
+
)
|
|
207
212
|
const loopTools = yield* makeLoopTools({
|
|
208
213
|
loopTools: options.loopTools,
|
|
209
214
|
skills: options.skills,
|
|
210
215
|
executorTools: capabilities.tools,
|
|
211
216
|
})
|
|
212
217
|
const promptTools: PromptTools = {
|
|
213
|
-
toolsDts:
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
: `${capabilities.toolsDts}\n\n${loopTools.dts}`,
|
|
218
|
+
toolsDts: [capabilities.toolsDts, loopTools.dts, mcpServers?.dts ?? ""]
|
|
219
|
+
.filter((dts) => dts !== "")
|
|
220
|
+
.join("\n\n"),
|
|
217
221
|
offers: (name) => capabilities.tools.includes(name),
|
|
218
222
|
skillsCatalog:
|
|
219
223
|
options.skills === undefined
|
|
220
224
|
? AgentSkills.renderCatalog(capabilities.skills)
|
|
221
225
|
: AgentSkills.renderProvidedCatalog(options.skills),
|
|
226
|
+
mcp: mcpServers?.prompt ?? "",
|
|
222
227
|
}
|
|
223
228
|
|
|
224
229
|
// Steering messages for the root agent. Sub-agents get their own mailbox.
|
|
@@ -286,6 +291,15 @@ export const makeWith = Effect.fnUntraced(function* <
|
|
|
286
291
|
// Images attached by `readFile` during the current script, spliced onto
|
|
287
292
|
// the Prompt as a user message once the tool result has been recorded.
|
|
288
293
|
const pendingImages: Array<ImageAttachment> = []
|
|
294
|
+
const onImage = (image: ImageAttachment) =>
|
|
295
|
+
Effect.sync(() => {
|
|
296
|
+
pendingImages.push(image)
|
|
297
|
+
})
|
|
298
|
+
// MCP results attach their images to this agent's next message.
|
|
299
|
+
const scriptLoopTools =
|
|
300
|
+
mcpServers === undefined
|
|
301
|
+
? loopTools.handlers
|
|
302
|
+
: { ...loopTools.handlers, ...mcpServers.handlers(onImage) }
|
|
289
303
|
// Whether a script ran in the current response. Their environment
|
|
290
304
|
// update is rendered once, after all of their tool results.
|
|
291
305
|
let scriptsRan = false
|
|
@@ -797,11 +811,8 @@ ${prompt}`,
|
|
|
797
811
|
}),
|
|
798
812
|
subagents,
|
|
799
813
|
onTaskComplete,
|
|
800
|
-
onImage
|
|
801
|
-
|
|
802
|
-
pendingImages.push(image)
|
|
803
|
-
}),
|
|
804
|
-
loopTools: loopTools.handlers,
|
|
814
|
+
onImage,
|
|
815
|
+
loopTools: scriptLoopTools,
|
|
805
816
|
}),
|
|
806
817
|
Stream.mkString,
|
|
807
818
|
)
|
|
@@ -1310,6 +1321,8 @@ interface PromptTools {
|
|
|
1310
1321
|
readonly toolsDts: string
|
|
1311
1322
|
readonly offers: (name: ExcludableTool) => boolean
|
|
1312
1323
|
readonly skillsCatalog: Option.Option<string>
|
|
1324
|
+
/** The MCP servers section, or `""` without servers. */
|
|
1325
|
+
readonly mcp: string
|
|
1313
1326
|
}
|
|
1314
1327
|
|
|
1315
1328
|
const when = (condition: boolean, text: string) => (condition ? text : "")
|
|
@@ -1372,7 +1385,12 @@ ${tools.toolsDts}
|
|
|
1372
1385
|
|
|
1373
1386
|
/** The global Fetch API available for making HTTP requests. */
|
|
1374
1387
|
declare const fetch: typeof globalThis.fetch
|
|
1375
|
-
\`\`\`${
|
|
1388
|
+
\`\`\`${when(
|
|
1389
|
+
tools.mcp !== "",
|
|
1390
|
+
`
|
|
1391
|
+
|
|
1392
|
+
${tools.mcp}`,
|
|
1393
|
+
)}${Option.match(tools.skillsCatalog, {
|
|
1376
1394
|
onNone: () => "",
|
|
1377
1395
|
onSome: (catalog) => `
|
|
1378
1396
|
|
|
@@ -1419,6 +1437,9 @@ const ReadSkillTools = Toolkit.make(
|
|
|
1419
1437
|
}),
|
|
1420
1438
|
)
|
|
1421
1439
|
|
|
1440
|
+
// Script names taken by MCP, whether or not servers are configured.
|
|
1441
|
+
const reservedToolNames: ReadonlySet<string> = new Set(["mcp", "searchTools"])
|
|
1442
|
+
|
|
1422
1443
|
/**
|
|
1423
1444
|
* Builds the loop-side handlers the executor puts in the sandbox, and their
|
|
1424
1445
|
* type declarations. Every call is decoded by `Toolkit.handle` before the
|
|
@@ -1432,6 +1453,13 @@ const makeLoopTools = Effect.fnUntraced(function* (options: {
|
|
|
1432
1453
|
const skills = options.skills ?? []
|
|
1433
1454
|
const callerTools = Object.keys(options.loopTools?.tools ?? {})
|
|
1434
1455
|
const names = skills.length > 0 ? [...callerTools, "readSkill"] : callerTools
|
|
1456
|
+
for (const name of [...options.executorTools, ...names]) {
|
|
1457
|
+
if (reservedToolNames.has(name)) {
|
|
1458
|
+
return yield* Effect.die(
|
|
1459
|
+
new Error(`Tool name "${name}" is reserved for MCP tools`),
|
|
1460
|
+
)
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1435
1463
|
for (const name of names) {
|
|
1436
1464
|
if (
|
|
1437
1465
|
options.executorTools.includes(name) ||
|
package/src/AgentExecutor.ts
CHANGED
|
@@ -1388,8 +1388,11 @@ function runScriptWorker(load: (id: string) => unknown): void {
|
|
|
1388
1388
|
fetch,
|
|
1389
1389
|
process: undefined,
|
|
1390
1390
|
}
|
|
1391
|
+
// MCP tools are named "<server>.<tool>" and bound as `mcp[server][tool]`.
|
|
1392
|
+
// Null prototypes keep names like `__proto__` and `constructor` safe.
|
|
1393
|
+
const mcp: Record<string, Record<string, unknown>> = Object.create(null)
|
|
1391
1394
|
for (const name of data.tools) {
|
|
1392
|
-
|
|
1395
|
+
const call = (params: unknown) =>
|
|
1393
1396
|
new Promise((resolve, reject) => {
|
|
1394
1397
|
const id = nextId++
|
|
1395
1398
|
pending.set(id, { resolve, reject })
|
|
@@ -1402,7 +1405,17 @@ function runScriptWorker(load: (id: string) => unknown): void {
|
|
|
1402
1405
|
maybeDone()
|
|
1403
1406
|
}
|
|
1404
1407
|
})
|
|
1408
|
+
const dot = name.indexOf(".")
|
|
1409
|
+
if (dot === -1) {
|
|
1410
|
+
sandbox[name] = call
|
|
1411
|
+
continue
|
|
1412
|
+
}
|
|
1413
|
+
const server = name.slice(0, dot)
|
|
1414
|
+
mcp[server] ??= Object.create(null)
|
|
1415
|
+
mcp[server]![name.slice(dot + 1)] = call
|
|
1405
1416
|
}
|
|
1417
|
+
// Only bound with servers, so `typeof mcp` tells scripts whether there are any.
|
|
1418
|
+
if (Object.keys(mcp).length > 0) sandbox["mcp"] = mcp
|
|
1406
1419
|
|
|
1407
1420
|
new vm.Script(data.source).runInNewContext(sandbox)
|
|
1408
1421
|
;(sandbox.main as () => Promise<void>)().then(
|
package/src/AgentTools.ts
CHANGED
|
@@ -207,6 +207,14 @@ export class ImageAttacher extends Context.Service<
|
|
|
207
207
|
*/
|
|
208
208
|
export const defaultBashTimeout: Duration.Duration = Duration.minutes(10)
|
|
209
209
|
|
|
210
|
+
/**
|
|
211
|
+
* The timeout of an MCP tool call when its server sets no `callTimeout`.
|
|
212
|
+
*
|
|
213
|
+
* @since 1.0.0
|
|
214
|
+
* @category Context
|
|
215
|
+
*/
|
|
216
|
+
export const defaultMcpCallTimeout: Duration.Duration = Duration.minutes(10)
|
|
217
|
+
|
|
210
218
|
/**
|
|
211
219
|
* The limits the `bash` and `gh` handlers apply to a single command. The
|
|
212
220
|
* executor sets them from its `limits` option.
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { assert, describe, it } from "@effect/vitest"
|
|
2
|
+
import * as NodeServices from "@effect/platform-node/NodeServices"
|
|
3
|
+
import * as ConfigProvider from "effect/ConfigProvider"
|
|
4
|
+
import * as Duration from "effect/Duration"
|
|
5
|
+
import * as Effect from "effect/Effect"
|
|
6
|
+
import * as FileSystem from "effect/FileSystem"
|
|
7
|
+
import * as Path from "effect/Path"
|
|
8
|
+
import * as Redacted from "effect/Redacted"
|
|
9
|
+
import * as McpConfig from "./McpConfig.ts"
|
|
10
|
+
import * as McpServers from "./McpServers.ts"
|
|
11
|
+
|
|
12
|
+
// =============================================================================
|
|
13
|
+
// The `clanka` CLI's MCP server configuration: the user file, the project
|
|
14
|
+
// `.mcp.json` and `--mcp-config` files, merged into the config handed to
|
|
15
|
+
// `McpServers.layer`. `enabled: false` is `--no-mcp` / `CLANKA_MCP=false`.
|
|
16
|
+
// The environment, `XDG_CONFIG_HOME` included, comes from the ConfigProvider.
|
|
17
|
+
// =============================================================================
|
|
18
|
+
|
|
19
|
+
interface Files {
|
|
20
|
+
readonly user?: unknown
|
|
21
|
+
readonly project?: unknown
|
|
22
|
+
readonly flags?: Readonly<Record<string, unknown>>
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Writes the files into a fresh directory and loads them, with `project/` as
|
|
27
|
+
* the cwd and `home/` as `XDG_CONFIG_HOME`. A string is written as it is,
|
|
28
|
+
* anything else as JSON.
|
|
29
|
+
*/
|
|
30
|
+
const load = (
|
|
31
|
+
files: Files,
|
|
32
|
+
options: {
|
|
33
|
+
readonly env?: Readonly<Record<string, string>>
|
|
34
|
+
readonly enabled?: boolean
|
|
35
|
+
} = {},
|
|
36
|
+
) =>
|
|
37
|
+
Effect.gen(function* () {
|
|
38
|
+
const fs = yield* FileSystem.FileSystem
|
|
39
|
+
const path = yield* Path.Path
|
|
40
|
+
const root = yield* fs.makeTempDirectoryScoped()
|
|
41
|
+
const write = Effect.fnUntraced(function* (file: string, content: unknown) {
|
|
42
|
+
yield* fs.makeDirectory(path.dirname(file), { recursive: true })
|
|
43
|
+
yield* fs.writeFileString(
|
|
44
|
+
file,
|
|
45
|
+
typeof content === "string" ? content : JSON.stringify(content),
|
|
46
|
+
)
|
|
47
|
+
})
|
|
48
|
+
const home = path.join(root, "home")
|
|
49
|
+
const cwd = path.join(root, "project")
|
|
50
|
+
yield* fs.makeDirectory(cwd, { recursive: true })
|
|
51
|
+
if (files.user !== undefined) {
|
|
52
|
+
yield* write(path.join(home, "clanka", "mcp.json"), files.user)
|
|
53
|
+
}
|
|
54
|
+
if (files.project !== undefined) {
|
|
55
|
+
yield* write(path.join(cwd, ".mcp.json"), files.project)
|
|
56
|
+
}
|
|
57
|
+
const flagFiles: Array<string> = []
|
|
58
|
+
for (const [name, content] of Object.entries(files.flags ?? {})) {
|
|
59
|
+
const file = path.join(root, "flags", name)
|
|
60
|
+
yield* write(file, content)
|
|
61
|
+
flagFiles.push(file)
|
|
62
|
+
}
|
|
63
|
+
const config = yield* McpConfig.load({
|
|
64
|
+
cwd,
|
|
65
|
+
files: flagFiles,
|
|
66
|
+
enabled: options.enabled ?? true,
|
|
67
|
+
}).pipe(
|
|
68
|
+
Effect.provideService(
|
|
69
|
+
ConfigProvider.ConfigProvider,
|
|
70
|
+
ConfigProvider.fromEnv({
|
|
71
|
+
env: { XDG_CONFIG_HOME: home, ...options.env },
|
|
72
|
+
}),
|
|
73
|
+
),
|
|
74
|
+
)
|
|
75
|
+
return { config, root }
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
const at = (value: unknown, path: string): unknown =>
|
|
79
|
+
path
|
|
80
|
+
.split(".")
|
|
81
|
+
.reduce<unknown>(
|
|
82
|
+
(value, key) => (value as Record<string, unknown> | undefined)?.[key],
|
|
83
|
+
value,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
const secret = (value: unknown, path: string): string =>
|
|
87
|
+
Redacted.value(at(value, path) as Redacted.Redacted<string>)
|
|
88
|
+
|
|
89
|
+
describe("McpConfig", () => {
|
|
90
|
+
it.effect("merges the user, project and flag files by precedence", () =>
|
|
91
|
+
Effect.gen(function* () {
|
|
92
|
+
const path = yield* Path.Path
|
|
93
|
+
const { config, root } = yield* load({
|
|
94
|
+
user: {
|
|
95
|
+
mcpServers: {
|
|
96
|
+
shared: {
|
|
97
|
+
command: "user-cmd",
|
|
98
|
+
args: ["--user"],
|
|
99
|
+
env: { FROM: "user" },
|
|
100
|
+
},
|
|
101
|
+
remote: {
|
|
102
|
+
url: "https://user.example/mcp",
|
|
103
|
+
headers: { Authorization: "Bearer user" },
|
|
104
|
+
disabled: true,
|
|
105
|
+
alwaysAllow: ["anything"],
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
project: {
|
|
110
|
+
mcpServers: {
|
|
111
|
+
shared: { command: "project-cmd" },
|
|
112
|
+
tool: { command: "project-tool" },
|
|
113
|
+
},
|
|
114
|
+
},
|
|
115
|
+
flags: {
|
|
116
|
+
"a.json": { mcpServers: { tool: { command: "a-tool" } } },
|
|
117
|
+
"nested/b.json": {
|
|
118
|
+
mcpServers: {
|
|
119
|
+
tool: { command: "b-tool", cwd: "work", callTimeout: 1500 },
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
})
|
|
124
|
+
assert.sameMembers(Object.keys(config), ["shared", "remote", "tool"])
|
|
125
|
+
|
|
126
|
+
// A higher-precedence entry replaces a lower one whole.
|
|
127
|
+
assert.nestedPropertyVal(config, "shared.type", "stdio")
|
|
128
|
+
assert.nestedPropertyVal(config, "shared.command", "project-cmd")
|
|
129
|
+
assert.notDeepNestedPropertyVal(config, "shared.args", ["--user"])
|
|
130
|
+
assert.notNestedProperty(config, "shared.env.FROM")
|
|
131
|
+
|
|
132
|
+
// `type` follows from `url`; unknown keys are ignored.
|
|
133
|
+
assert.nestedPropertyVal(config, "remote.type", "http")
|
|
134
|
+
assert.nestedPropertyVal(config, "remote.url", "https://user.example/mcp")
|
|
135
|
+
assert.strictEqual(
|
|
136
|
+
secret(config, "remote.headers.Authorization"),
|
|
137
|
+
"Bearer user",
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
// A later flag wins; its relative `cwd` resolves against its own file.
|
|
141
|
+
assert.nestedPropertyVal(config, "tool.command", "b-tool")
|
|
142
|
+
assert.nestedPropertyVal(
|
|
143
|
+
config,
|
|
144
|
+
"tool.cwd",
|
|
145
|
+
path.join(root, "flags", "nested", "work"),
|
|
146
|
+
)
|
|
147
|
+
assert.strictEqual(
|
|
148
|
+
Duration.toMillis(at(config, "tool.callTimeout") as Duration.Duration),
|
|
149
|
+
1500,
|
|
150
|
+
)
|
|
151
|
+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
it.live("expands environment variables before decoding", () =>
|
|
155
|
+
Effect.gen(function* () {
|
|
156
|
+
const { config } = yield* load(
|
|
157
|
+
{
|
|
158
|
+
project: {
|
|
159
|
+
mcpServers: {
|
|
160
|
+
local: {
|
|
161
|
+
command: "${BIN:-node}",
|
|
162
|
+
args: ["--token=${TOKEN}", "$TOKEN"],
|
|
163
|
+
env: { KEY: "${TOKEN}" },
|
|
164
|
+
cwd: "${WORK}",
|
|
165
|
+
},
|
|
166
|
+
remote: {
|
|
167
|
+
url: "https://${HOST:-example.com}/mcp",
|
|
168
|
+
headers: { Authorization: "Bearer ${TOKEN}" },
|
|
169
|
+
},
|
|
170
|
+
missing: { command: "node", args: ["${NOT_SET}"] },
|
|
171
|
+
},
|
|
172
|
+
},
|
|
173
|
+
},
|
|
174
|
+
{ env: { TOKEN: "t0k", WORK: "/work" } },
|
|
175
|
+
)
|
|
176
|
+
assert.nestedPropertyVal(config, "local.command", "node")
|
|
177
|
+
// Bare `$VAR` is left alone.
|
|
178
|
+
assert.deepNestedPropertyVal(config, "local.args", [
|
|
179
|
+
"--token=t0k",
|
|
180
|
+
"$TOKEN",
|
|
181
|
+
])
|
|
182
|
+
assert.strictEqual(secret(config, "local.env.KEY"), "t0k")
|
|
183
|
+
assert.nestedPropertyVal(config, "local.cwd", "/work")
|
|
184
|
+
assert.nestedPropertyVal(config, "remote.url", "https://example.com/mcp")
|
|
185
|
+
assert.strictEqual(
|
|
186
|
+
secret(config, "remote.headers.Authorization"),
|
|
187
|
+
"Bearer t0k",
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
// A missing variable fails only that server.
|
|
191
|
+
const status = yield* Effect.gen(function* () {
|
|
192
|
+
const servers = yield* McpServers.McpServers
|
|
193
|
+
return yield* servers.status
|
|
194
|
+
}).pipe(Effect.provide(McpServers.layer({ missing: config["missing"]! })))
|
|
195
|
+
const missing = status["missing"]
|
|
196
|
+
assert.strictEqual(missing?._tag, "Failed")
|
|
197
|
+
if (missing?._tag === "Failed") {
|
|
198
|
+
assert.include(missing.error, "environment variable NOT_SET is not set")
|
|
199
|
+
}
|
|
200
|
+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
it.effect("keeps servers named like Object.prototype members", () =>
|
|
204
|
+
Effect.gen(function* () {
|
|
205
|
+
const { config } = yield* load({
|
|
206
|
+
project:
|
|
207
|
+
'{ "mcpServers": { "__proto__": { "command": "proto-cmd" }, "constructor": { "command": "constructor-cmd" } } }',
|
|
208
|
+
})
|
|
209
|
+
assert.sameMembers(Object.keys(config), ["__proto__", "constructor"])
|
|
210
|
+
assert.strictEqual(at(config, "__proto__.command"), "proto-cmd")
|
|
211
|
+
assert.strictEqual(at(config, "constructor.command"), "constructor-cmd")
|
|
212
|
+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
it.effect("an invalid file stops the CLI unless MCP is disabled", () =>
|
|
216
|
+
Effect.gen(function* () {
|
|
217
|
+
const invalidJson = yield* load({ project: "{ not json" }).pipe(
|
|
218
|
+
Effect.flip,
|
|
219
|
+
)
|
|
220
|
+
assert.include(invalidJson.message, ".mcp.json")
|
|
221
|
+
|
|
222
|
+
const invalidEntry = yield* load({
|
|
223
|
+
flags: { "bad.json": { mcpServers: { broken: { command: 42 } } } },
|
|
224
|
+
}).pipe(Effect.flip)
|
|
225
|
+
assert.include(invalidEntry.message, "bad.json")
|
|
226
|
+
assert.include(invalidEntry.message, "broken")
|
|
227
|
+
|
|
228
|
+
const disabled = yield* load(
|
|
229
|
+
{
|
|
230
|
+
project: "{ not json",
|
|
231
|
+
flags: { "bad.json": { mcpServers: { broken: { command: 42 } } } },
|
|
232
|
+
},
|
|
233
|
+
{ enabled: false },
|
|
234
|
+
)
|
|
235
|
+
assert.deepStrictEqual(disabled.config, {})
|
|
236
|
+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
|
|
237
|
+
)
|
|
238
|
+
})
|
package/src/McpConfig.ts
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The MCP server configuration of the `clanka` CLI.
|
|
3
|
+
*
|
|
4
|
+
* Servers come from the user file (`$XDG_CONFIG_HOME/clanka/mcp.json`), the
|
|
5
|
+
* project `.mcp.json` in the cwd and `--mcp-config` files, in increasing
|
|
6
|
+
* precedence. The format is `{ "mcpServers": { "<name>": { ... } } }`, as used
|
|
7
|
+
* by Claude Code and Cursor.
|
|
8
|
+
*
|
|
9
|
+
* @since 1.0.0
|
|
10
|
+
*/
|
|
11
|
+
import * as Config from "effect/Config"
|
|
12
|
+
import * as Data from "effect/Data"
|
|
13
|
+
import * as Effect from "effect/Effect"
|
|
14
|
+
import * as FileSystem from "effect/FileSystem"
|
|
15
|
+
import * as Option from "effect/Option"
|
|
16
|
+
import * as Path from "effect/Path"
|
|
17
|
+
import * as Schema from "effect/Schema"
|
|
18
|
+
import * as Struct from "effect/Struct"
|
|
19
|
+
import type * as McpServers from "./McpServers.ts"
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* An MCP config file that cannot be read or decoded.
|
|
23
|
+
*
|
|
24
|
+
* @since 1.0.0
|
|
25
|
+
* @category Errors
|
|
26
|
+
*/
|
|
27
|
+
export class McpConfigError extends Schema.TaggedError<McpConfigError>()(
|
|
28
|
+
"McpConfigError",
|
|
29
|
+
{ message: Schema.String },
|
|
30
|
+
) {}
|
|
31
|
+
|
|
32
|
+
const ConfigFile = Schema.fromJsonString(
|
|
33
|
+
Schema.Struct({
|
|
34
|
+
mcpServers: Schema.optionalKey(
|
|
35
|
+
Schema.Record(Schema.String, Schema.Unknown),
|
|
36
|
+
),
|
|
37
|
+
}),
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
const RedactedStrings = Schema.Record(
|
|
41
|
+
Schema.String,
|
|
42
|
+
Schema.RedactedFromValue(Schema.String),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
// Unknown keys, such as `disabled` or `alwaysAllow`, are dropped.
|
|
46
|
+
const FileEntry = Schema.Struct({
|
|
47
|
+
type: Schema.optionalKey(Schema.Literals(["stdio", "http", "sse"])),
|
|
48
|
+
command: Schema.optionalKey(Schema.String),
|
|
49
|
+
args: Schema.optionalKey(Schema.Array(Schema.String)),
|
|
50
|
+
env: Schema.optionalKey(RedactedStrings),
|
|
51
|
+
cwd: Schema.optionalKey(Schema.String),
|
|
52
|
+
url: Schema.optionalKey(Schema.String),
|
|
53
|
+
headers: Schema.optionalKey(RedactedStrings),
|
|
54
|
+
connectTimeout: Schema.optionalKey(Schema.DurationFromMillis),
|
|
55
|
+
callTimeout: Schema.optionalKey(Schema.DurationFromMillis),
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
const decodeFile = Schema.decodeUnknownEffect(ConfigFile)
|
|
59
|
+
const decodeFileEntry = Schema.decodeUnknownEffect(FileEntry)
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Reads and merges the config files. A later source replaces a server of the
|
|
63
|
+
* same name whole. `enabled: false` (`--no-mcp`) reads nothing.
|
|
64
|
+
*
|
|
65
|
+
* `${VAR}` and `${VAR:-default}` are expanded in `command`, `args`, `env`,
|
|
66
|
+
* `cwd`, `url` and `headers`; a server referring to a variable that is not
|
|
67
|
+
* set is unavailable. A relative `cwd` resolves against the directory of the
|
|
68
|
+
* file that defines it.
|
|
69
|
+
*
|
|
70
|
+
* @since 1.0.0
|
|
71
|
+
* @category Loading
|
|
72
|
+
*/
|
|
73
|
+
export const load = Effect.fnUntraced(function* (options: {
|
|
74
|
+
readonly cwd: string
|
|
75
|
+
/** The `--mcp-config` files, in the order given. */
|
|
76
|
+
readonly files: ReadonlyArray<string>
|
|
77
|
+
readonly enabled: boolean
|
|
78
|
+
}): Effect.fn.Return<
|
|
79
|
+
Record<string, McpServers.ServerEntry>,
|
|
80
|
+
McpConfigError,
|
|
81
|
+
FileSystem.FileSystem | Path.Path
|
|
82
|
+
> {
|
|
83
|
+
if (!options.enabled) return {}
|
|
84
|
+
const fs = yield* FileSystem.FileSystem
|
|
85
|
+
const path = yield* Path.Path
|
|
86
|
+
|
|
87
|
+
const configHome = yield* Config.NonEmptyString("XDG_CONFIG_HOME").pipe(
|
|
88
|
+
Config.orElse(() =>
|
|
89
|
+
Config.NonEmptyString("HOME").pipe(
|
|
90
|
+
Config.map((home) => path.join(home, ".config")),
|
|
91
|
+
),
|
|
92
|
+
),
|
|
93
|
+
Config.option,
|
|
94
|
+
Effect.orElseSucceed(() => Option.none<string>()),
|
|
95
|
+
)
|
|
96
|
+
const sources = [
|
|
97
|
+
...Option.match(configHome, {
|
|
98
|
+
onNone: () => [],
|
|
99
|
+
onSome: (home) => [
|
|
100
|
+
{ file: path.join(home, "clanka", "mcp.json"), required: false },
|
|
101
|
+
],
|
|
102
|
+
}),
|
|
103
|
+
{ file: path.join(options.cwd, ".mcp.json"), required: false },
|
|
104
|
+
...options.files.map((file) => ({
|
|
105
|
+
file: path.resolve(options.cwd, file),
|
|
106
|
+
required: true,
|
|
107
|
+
})),
|
|
108
|
+
]
|
|
109
|
+
|
|
110
|
+
const servers: Record<string, McpServers.ServerEntry> = Object.create(null)
|
|
111
|
+
for (const { file, required } of sources) {
|
|
112
|
+
const fail = (message: string) =>
|
|
113
|
+
new McpConfigError({ message: `${file}: ${message}` })
|
|
114
|
+
const text = yield* fs.readFileString(file).pipe(
|
|
115
|
+
Effect.catchReason("PlatformError", "NotFound", (_, error) =>
|
|
116
|
+
required ? Effect.fail(error) : Effect.void,
|
|
117
|
+
),
|
|
118
|
+
Effect.mapError((error) => fail(error.message)),
|
|
119
|
+
)
|
|
120
|
+
if (text === undefined) continue
|
|
121
|
+
const { mcpServers } = yield* decodeFile(text).pipe(
|
|
122
|
+
Effect.mapError((error) => fail(error.message)),
|
|
123
|
+
)
|
|
124
|
+
for (const [name, entry] of Object.entries(mcpServers ?? {})) {
|
|
125
|
+
servers[name] = yield* decodeEntry(entry, {
|
|
126
|
+
directory: path.dirname(file),
|
|
127
|
+
fail: (message) => fail(`MCP server "${name}": ${message}`),
|
|
128
|
+
resolve: path.resolve,
|
|
129
|
+
})
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return servers
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
const decodeEntry = Effect.fnUntraced(
|
|
136
|
+
function* (
|
|
137
|
+
raw: unknown,
|
|
138
|
+
options: {
|
|
139
|
+
readonly directory: string
|
|
140
|
+
readonly fail: (message: string) => McpConfigError
|
|
141
|
+
readonly resolve: (...segments: ReadonlyArray<string>) => string
|
|
142
|
+
},
|
|
143
|
+
): Effect.fn.Return<
|
|
144
|
+
McpServers.ServerEntry,
|
|
145
|
+
McpConfigError | MissingVariable
|
|
146
|
+
> {
|
|
147
|
+
const entry = yield* decodeFileEntry(yield* expandEntry(raw)).pipe(
|
|
148
|
+
Effect.mapError((error) => options.fail(error.message)),
|
|
149
|
+
)
|
|
150
|
+
const type =
|
|
151
|
+
entry.type ??
|
|
152
|
+
(entry.command !== undefined
|
|
153
|
+
? "stdio"
|
|
154
|
+
: entry.url !== undefined
|
|
155
|
+
? "http"
|
|
156
|
+
: undefined)
|
|
157
|
+
switch (type) {
|
|
158
|
+
case undefined:
|
|
159
|
+
return yield* options.fail("needs a command or a url")
|
|
160
|
+
case "sse":
|
|
161
|
+
return { type: "unavailable", error: "SSE transport is not supported" }
|
|
162
|
+
case "stdio": {
|
|
163
|
+
if (entry.command === undefined) {
|
|
164
|
+
return yield* options.fail("a stdio server needs a command")
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
...Struct.omit(entry, ["type", "url", "headers", "cwd"]),
|
|
168
|
+
type: "stdio",
|
|
169
|
+
command: entry.command,
|
|
170
|
+
...(entry.cwd !== undefined
|
|
171
|
+
? { cwd: options.resolve(options.directory, entry.cwd) }
|
|
172
|
+
: {}),
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
case "http": {
|
|
176
|
+
if (entry.url === undefined) {
|
|
177
|
+
return yield* options.fail("an http server needs a url")
|
|
178
|
+
}
|
|
179
|
+
return {
|
|
180
|
+
...Struct.omit(entry, ["type", "command", "args", "env", "cwd"]),
|
|
181
|
+
type: "http",
|
|
182
|
+
url: entry.url,
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
},
|
|
187
|
+
Effect.catchTag("MissingVariable", (missing) =>
|
|
188
|
+
Effect.succeed<McpServers.ServerEntry>({
|
|
189
|
+
type: "unavailable",
|
|
190
|
+
error: `environment variable ${missing.variable} is not set`,
|
|
191
|
+
}),
|
|
192
|
+
),
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
// =============================================================================
|
|
196
|
+
// Environment variables
|
|
197
|
+
// =============================================================================
|
|
198
|
+
|
|
199
|
+
class MissingVariable extends Data.TaggedError("MissingVariable")<{
|
|
200
|
+
readonly variable: string
|
|
201
|
+
}> {}
|
|
202
|
+
|
|
203
|
+
const variablePattern = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g
|
|
204
|
+
|
|
205
|
+
const lookup = (name: string) =>
|
|
206
|
+
Config.String(name).pipe(
|
|
207
|
+
Config.option,
|
|
208
|
+
Effect.orElseSucceed(() => Option.none<string>()),
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
const expand = Effect.fnUntraced(function* (text: string) {
|
|
212
|
+
let result = ""
|
|
213
|
+
let last = 0
|
|
214
|
+
for (const match of text.matchAll(variablePattern)) {
|
|
215
|
+
const [whole, name, fallback] = match
|
|
216
|
+
const value = Option.filter(yield* lookup(name!), (value) =>
|
|
217
|
+
fallback === undefined ? true : value !== "",
|
|
218
|
+
)
|
|
219
|
+
if (Option.isNone(value) && fallback === undefined) {
|
|
220
|
+
return yield* new MissingVariable({ variable: name! })
|
|
221
|
+
}
|
|
222
|
+
result +=
|
|
223
|
+
text.slice(last, match.index) + Option.getOrElse(value, () => fallback!)
|
|
224
|
+
last = match.index + whole.length
|
|
225
|
+
}
|
|
226
|
+
return result + text.slice(last)
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
const expandStrings = Effect.fnUntraced(function* (value: unknown) {
|
|
230
|
+
if (typeof value === "string") return yield* expand(value)
|
|
231
|
+
if (Array.isArray(value)) {
|
|
232
|
+
return yield* Effect.forEach(value, (item: unknown) =>
|
|
233
|
+
typeof item === "string" ? expand(item) : Effect.succeed(item),
|
|
234
|
+
)
|
|
235
|
+
}
|
|
236
|
+
if (typeof value === "object" && value !== null) {
|
|
237
|
+
const result: Record<string, unknown> = {}
|
|
238
|
+
for (const [key, item] of Object.entries(value)) {
|
|
239
|
+
result[key] = typeof item === "string" ? yield* expand(item) : item
|
|
240
|
+
}
|
|
241
|
+
return result
|
|
242
|
+
}
|
|
243
|
+
return value
|
|
244
|
+
})
|
|
245
|
+
|
|
246
|
+
const expandedFields = ["command", "args", "env", "cwd", "url", "headers"]
|
|
247
|
+
|
|
248
|
+
const expandEntry = Effect.fnUntraced(function* (raw: unknown) {
|
|
249
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return raw
|
|
250
|
+
const entry: Record<string, unknown> = { ...raw }
|
|
251
|
+
for (const field of expandedFields) {
|
|
252
|
+
if (field in entry) entry[field] = yield* expandStrings(entry[field])
|
|
253
|
+
}
|
|
254
|
+
return entry
|
|
255
|
+
})
|