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.
Files changed (92) hide show
  1. package/README.md +49 -0
  2. package/dist/Acp.d.ts +1 -1
  3. package/dist/Acp.d.ts.map +1 -1
  4. package/dist/Acp.js +122 -7
  5. package/dist/Acp.js.map +1 -1
  6. package/dist/Acp.test.js +240 -0
  7. package/dist/Acp.test.js.map +1 -1
  8. package/dist/Agent.d.ts.map +1 -1
  9. package/dist/Agent.js +26 -8
  10. package/dist/Agent.js.map +1 -1
  11. package/dist/AgentExecutor.js +15 -1
  12. package/dist/AgentExecutor.js.map +1 -1
  13. package/dist/AgentTools.d.ts +7 -0
  14. package/dist/AgentTools.d.ts.map +1 -1
  15. package/dist/AgentTools.js +7 -0
  16. package/dist/AgentTools.js.map +1 -1
  17. package/dist/McpConfig.d.ts +36 -0
  18. package/dist/McpConfig.d.ts.map +1 -0
  19. package/dist/McpConfig.js +182 -0
  20. package/dist/McpConfig.js.map +1 -0
  21. package/dist/McpConfig.test.d.ts +2 -0
  22. package/dist/McpConfig.test.d.ts.map +1 -0
  23. package/dist/McpConfig.test.js +163 -0
  24. package/dist/McpConfig.test.js.map +1 -0
  25. package/dist/McpServers.d.ts +176 -0
  26. package/dist/McpServers.d.ts.map +1 -0
  27. package/dist/McpServers.js +707 -0
  28. package/dist/McpServers.js.map +1 -0
  29. package/dist/McpServers.test.d.ts +2 -0
  30. package/dist/McpServers.test.d.ts.map +1 -0
  31. package/dist/McpServers.test.js +717 -0
  32. package/dist/McpServers.test.js.map +1 -0
  33. package/dist/TypeBuilder.d.ts +9 -0
  34. package/dist/TypeBuilder.d.ts.map +1 -1
  35. package/dist/TypeBuilder.js +24 -11
  36. package/dist/TypeBuilder.js.map +1 -1
  37. package/dist/TypeBuilder.test.js +33 -0
  38. package/dist/TypeBuilder.test.js.map +1 -1
  39. package/dist/bin/{Effect-zUBunSAW.mjs → Effect-DuThyCJ1.mjs} +87 -9
  40. package/dist/bin/Effect-DuThyCJ1.mjs.map +1 -0
  41. package/dist/bin/McpClient-CIiPyMDJ.mjs +36 -0
  42. package/dist/bin/McpClient-CIiPyMDJ.mjs.map +1 -0
  43. package/dist/bin/{OutputFormatter-BPdc6RmH.mjs → OutputFormatter-BvIjvUmT.mjs} +3 -3
  44. package/dist/bin/{OutputFormatter-BPdc6RmH.mjs.map → OutputFormatter-BvIjvUmT.mjs.map} +1 -1
  45. package/dist/bin/{Schema-C2Y2y3tU.mjs → Schema-DcXUXpRg.mjs} +831 -35
  46. package/dist/bin/Schema-DcXUXpRg.mjs.map +1 -0
  47. package/dist/bin/{SemanticSearch-BKZxP19F.mjs → SemanticSearch-CdGA4CIC.mjs} +5 -5
  48. package/dist/bin/{SemanticSearch-BKZxP19F.mjs.map → SemanticSearch-CdGA4CIC.mjs.map} +1 -1
  49. package/dist/bin/{Stream-BvmRbTMu.mjs → Stream-I9SRMlLj.mjs} +20 -22
  50. package/dist/bin/Stream-I9SRMlLj.mjs.map +1 -0
  51. package/dist/bin/cli.mjs +17646 -802
  52. package/dist/bin/cli.mjs.map +1 -1
  53. package/dist/bin/{index.min-DbZbUHX3.mjs → index.min-Bkz7vIWv.mjs} +5 -5
  54. package/dist/bin/{index.min-DbZbUHX3.mjs.map → index.min-Bkz7vIWv.mjs.map} +1 -1
  55. package/dist/bin/rolldown-runtime-zY4HT0JA.mjs +30 -0
  56. package/dist/bin/{turndown.cjs-DK29wZw3.mjs → turndown.cjs-LntFxFyd.mjs} +2 -2
  57. package/dist/bin/{turndown.cjs-DK29wZw3.mjs.map → turndown.cjs-LntFxFyd.mjs.map} +1 -1
  58. package/dist/cli.js +24 -2
  59. package/dist/cli.js.map +1 -1
  60. package/dist/fixtures/McpFakeServer.d.ts +47 -0
  61. package/dist/fixtures/McpFakeServer.d.ts.map +1 -0
  62. package/dist/fixtures/McpFakeServer.js +112 -0
  63. package/dist/fixtures/McpFakeServer.js.map +1 -0
  64. package/dist/fixtures/McpStdioServer.d.ts +2 -0
  65. package/dist/fixtures/McpStdioServer.d.ts.map +1 -0
  66. package/dist/fixtures/McpStdioServer.js +53 -0
  67. package/dist/fixtures/McpStdioServer.js.map +1 -0
  68. package/dist/index.d.ts +4 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +4 -0
  71. package/dist/index.js.map +1 -1
  72. package/package.json +1 -1
  73. package/src/Acp.test.ts +348 -0
  74. package/src/Acp.ts +154 -5
  75. package/src/Agent.ts +38 -10
  76. package/src/AgentExecutor.ts +14 -1
  77. package/src/AgentTools.ts +8 -0
  78. package/src/McpConfig.test.ts +238 -0
  79. package/src/McpConfig.ts +255 -0
  80. package/src/McpServers.test.ts +1050 -0
  81. package/src/McpServers.ts +1072 -0
  82. package/src/TypeBuilder.test.ts +70 -0
  83. package/src/TypeBuilder.ts +41 -14
  84. package/src/cli.ts +46 -0
  85. package/src/fixtures/McpFakeServer.ts +162 -0
  86. package/src/fixtures/McpStdioServer.ts +60 -0
  87. package/src/index.ts +5 -0
  88. package/dist/bin/Effect-zUBunSAW.mjs.map +0 -1
  89. package/dist/bin/McpClient-CnP2P7c9.mjs +0 -14179
  90. package/dist/bin/McpClient-CnP2P7c9.mjs.map +0 -1
  91. package/dist/bin/Schema-C2Y2y3tU.mjs.map +0 -1
  92. package/dist/bin/Stream-BvmRbTMu.mjs.map +0 -1
package/src/Acp.test.ts CHANGED
@@ -1,11 +1,19 @@
1
1
  import { assert, describe, it } from "@effect/vitest"
2
2
  import * as NodeServices from "@effect/platform-node/NodeServices"
3
+ import type * as Cause from "effect/Cause"
3
4
  import * as Context from "effect/Context"
5
+ import * as Deferred from "effect/Deferred"
4
6
  import * as Effect from "effect/Effect"
5
7
  import * as FileSystem from "effect/FileSystem"
6
8
  import * as Fiber from "effect/Fiber"
7
9
  import * as Layer from "effect/Layer"
10
+ import * as Logger from "effect/Logger"
8
11
  import * as Option from "effect/Option"
12
+ import * as Path from "effect/Path"
13
+ import * as Queue from "effect/Queue"
14
+ import * as Schedule from "effect/Schedule"
15
+ import * as Sink from "effect/Sink"
16
+ import * as Stdio from "effect/Stdio"
9
17
  import * as Stream from "effect/Stream"
10
18
  import * as FetchHttpClient from "effect/http/FetchHttpClient"
11
19
  import * as Prompt from "effect/ai/Prompt"
@@ -17,6 +25,7 @@ import * as Acp from "./Acp.ts"
17
25
  import * as Agent from "./Agent.ts"
18
26
  import * as AgentExecutor from "./AgentExecutor.ts"
19
27
  import * as Compaction from "./Compaction.ts"
28
+ import { listenHttp, makeFakeServer, text } from "./fixtures/McpFakeServer.ts"
20
29
 
21
30
  type Message = {
22
31
  readonly id?: number
@@ -949,4 +958,343 @@ await changeDirectory("sub")`),
949
958
  ),
950
959
  ),
951
960
  )
961
+
962
+ it.effect("reports prompts still running when stdin ends", () =>
963
+ withStore(
964
+ Effect.gen(function* () {
965
+ const modelCalled = yield* Deferred.make<void>()
966
+ const languageModel = yield* LanguageModel.make({
967
+ generateText: () => Effect.succeed([]),
968
+ streamText: () =>
969
+ Stream.fromEffect(Deferred.succeed(modelCalled, undefined)).pipe(
970
+ Stream.drain,
971
+ Stream.concat(Stream.never),
972
+ ),
973
+ })
974
+ const modelLayer = Layer.mergeAll(
975
+ Layer.succeed(LanguageModel.LanguageModel, languageModel),
976
+ Layer.succeed(Model.ProviderName, "test"),
977
+ Layer.succeed(Model.ModelName, "model"),
978
+ )
979
+
980
+ const decoder = new TextDecoder()
981
+ const decode = (chunk: string | Uint8Array) =>
982
+ typeof chunk === "string" ? chunk : decoder.decode(chunk)
983
+ const stdin = yield* Queue.unbounded<Uint8Array, Cause.Done>()
984
+ const stdout = yield* Queue.unbounded<string>()
985
+ const stdoutLines: Array<string> = []
986
+ // Both the stderr sink and log output reach stderr in the CLI.
987
+ const stderr: Array<string> = []
988
+ const stdio = Stdio.layerTest({
989
+ stdin: Stream.fromQueue(stdin),
990
+ stdout: () =>
991
+ Sink.forEach((chunk) =>
992
+ Effect.sync(() => {
993
+ for (const line of decode(chunk).split("\n")) {
994
+ if (line === "") continue
995
+ stdoutLines.push(line)
996
+ Queue.offerUnsafe(stdout, line)
997
+ }
998
+ }),
999
+ ),
1000
+ stderr: () =>
1001
+ Sink.forEach((chunk) =>
1002
+ Effect.sync(() => {
1003
+ stderr.push(decode(chunk))
1004
+ }),
1005
+ ),
1006
+ })
1007
+ const logger = Logger.layer([
1008
+ Logger.make((options) => {
1009
+ stderr.push(Logger.formatSimple.log(options))
1010
+ }),
1011
+ ])
1012
+
1013
+ const send = (message: object) =>
1014
+ Queue.offer(
1015
+ stdin,
1016
+ new TextEncoder().encode(
1017
+ `${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`,
1018
+ ),
1019
+ )
1020
+ const response = (id: number) =>
1021
+ Queue.take(stdout).pipe(
1022
+ Effect.map((line): Message => JSON.parse(line)),
1023
+ Effect.repeat({ until: (message) => message.id === id }),
1024
+ )
1025
+
1026
+ const server = yield* Acp.runStdio({
1027
+ version: "test",
1028
+ defaultModel: "test:model",
1029
+ defaultThoughtLevel: "medium",
1030
+ makeAgent: () =>
1031
+ Agent.make.pipe(
1032
+ Effect.provideService(AgentExecutor.AgentExecutor, executor),
1033
+ ),
1034
+ makeModel: () =>
1035
+ Option.some(
1036
+ Layer.merge(modelLayer, Agent.layerSubagentModel(modelLayer)),
1037
+ ),
1038
+ }).pipe(Effect.provide([stdio, logger]), Effect.forkChild)
1039
+
1040
+ yield* send({ id: 1, method: "session/new", params: { cwd: "/tmp" } })
1041
+ const sessionId: string = (yield* response(1)).result.sessionId
1042
+ yield* send({
1043
+ id: 2,
1044
+ method: "session/prompt",
1045
+ params: { sessionId, prompt: [{ type: "text", text: "hello" }] },
1046
+ })
1047
+ yield* Deferred.await(modelCalled)
1048
+ yield* Queue.end(stdin)
1049
+ yield* Fiber.join(server)
1050
+
1051
+ for (const line of stdoutLines) {
1052
+ assert.strictEqual(JSON.parse(line).jsonrpc, "2.0")
1053
+ }
1054
+ assert.isTrue(
1055
+ stderr.some((line) => line.includes(sessionId)),
1056
+ `expected a stderr diagnostic naming session ${sessionId}, got: ${JSON.stringify(stderr)}`,
1057
+ )
1058
+ }),
1059
+ ),
1060
+ )
1061
+ })
1062
+
1063
+ // --- MCP servers ---------------------------------------------------------------
1064
+
1065
+ const systemText = (prompt: Prompt.Prompt): string =>
1066
+ prompt.content
1067
+ .filter((message) => message.role === "system")
1068
+ .map((message) => message.content)
1069
+ .join("\n")
1070
+
1071
+ const isRunning = (pid: number): boolean => {
1072
+ try {
1073
+ process.kill(pid, 0)
1074
+ return true
1075
+ } catch {
1076
+ return false
1077
+ }
1078
+ }
1079
+
1080
+ const exited = (pid: number) =>
1081
+ Effect.sync(() => isRunning(pid)).pipe(
1082
+ Effect.repeat({
1083
+ while: (running) => running,
1084
+ schedule: Schedule.spaced("50 millis"),
1085
+ }),
1086
+ Effect.timeout("3 seconds"),
1087
+ )
1088
+
1089
+ const remoteServer = (path?: string) =>
1090
+ Effect.acquireRelease(
1091
+ Effect.promise(() =>
1092
+ listenHttp(
1093
+ makeFakeServer({
1094
+ tools: [{ name: "ping", call: () => text("pong") }],
1095
+ }),
1096
+ path,
1097
+ ),
1098
+ ),
1099
+ (remote) => Effect.promise(remote.close),
1100
+ )
1101
+
1102
+ /**
1103
+ * An ACP stdio entry running the fixture server, which writes its pid and cwd
1104
+ * to `out`.
1105
+ */
1106
+ const stdioServer = (path: Path.Path, name: string, out: string) => ({
1107
+ name,
1108
+ command: process.execPath,
1109
+ args: [path.join(import.meta.dirname, "fixtures", "McpStdioServer.ts")],
1110
+ env: [{ name: "FIXTURE_OUT", value: out }],
1111
+ })
1112
+
1113
+ const readStarted = (out: string) =>
1114
+ Effect.gen(function* () {
1115
+ const fs = yield* FileSystem.FileSystem
1116
+ return JSON.parse(yield* fs.readFileString(out)) as {
1117
+ readonly pid: number
1118
+ readonly cwd: string
1119
+ }
1120
+ })
1121
+
1122
+ describe("Acp MCP servers", () => {
1123
+ it.live("connects stdio and http servers and reports failed ones once", () =>
1124
+ withStore(
1125
+ Effect.gen(function* () {
1126
+ const fs = yield* FileSystem.FileSystem
1127
+ const path = yield* Path.Path
1128
+ const cwd = yield* fs.makeTempDirectoryScoped()
1129
+ const out = path.join(cwd, "started.json")
1130
+ const remote = yield* remoteServer()
1131
+ const systems: Array<string> = []
1132
+ const server = yield* makeServer((options) => {
1133
+ systems.push(systemText(options.prompt))
1134
+ return assistantSays("ok")
1135
+ })
1136
+
1137
+ const init = yield* server.request(1, "initialize", {
1138
+ protocolVersion: 1,
1139
+ })
1140
+ assert.deepStrictEqual(init.result.agentCapabilities.mcpCapabilities, {
1141
+ http: true,
1142
+ sse: false,
1143
+ })
1144
+ assert.isDefined(
1145
+ init.result.agentCapabilities.sessionCapabilities?.close,
1146
+ )
1147
+
1148
+ const created = yield* server.request(2, "session/new", {
1149
+ cwd,
1150
+ mcpServers: [
1151
+ // stdio has no `type`.
1152
+ stdioServer(path, "acpstdio", out),
1153
+ {
1154
+ type: "http",
1155
+ name: "acphttp",
1156
+ url: remote.url,
1157
+ headers: [{ name: "Authorization", value: "Bearer secret" }],
1158
+ },
1159
+ {
1160
+ type: "sse",
1161
+ name: "acplegacy",
1162
+ url: "http://127.0.0.1:9/sse",
1163
+ headers: [],
1164
+ },
1165
+ // A later duplicate is skipped.
1166
+ {
1167
+ name: "acpstdio",
1168
+ command: "/nonexistent/clanka-mcp",
1169
+ args: [],
1170
+ env: [],
1171
+ },
1172
+ ],
1173
+ })
1174
+ assert.isUndefined(created.error)
1175
+ const sessionId: string = created.result.sessionId
1176
+ for (const id of [3, 4]) {
1177
+ yield* server.request(id, "session/prompt", {
1178
+ sessionId,
1179
+ prompt: [{ type: "text", text: "hello" }],
1180
+ })
1181
+ }
1182
+
1183
+ const failures = server
1184
+ .updates(sessionId)
1185
+ .filter(
1186
+ (u) =>
1187
+ u.sessionUpdate === "agent_thought_chunk" &&
1188
+ String(u.content.text).includes("MCP server"),
1189
+ )
1190
+ .map((u) => String(u.content.text))
1191
+ assert.strictEqual(failures.length, 1)
1192
+ assert.include(
1193
+ failures[0],
1194
+ 'MCP server "acplegacy" failed: SSE transport is not supported',
1195
+ )
1196
+ assert.notInclude(failures[0], "acpstdio")
1197
+
1198
+ assert.include(systems[0], "acpstdio")
1199
+ assert.include(systems[0], "acphttp")
1200
+ // Stdio servers run in the session's cwd.
1201
+ const started = yield* readStarted(out)
1202
+ assert.strictEqual(started.cwd, yield* fs.realPath(cwd))
1203
+ assert.isNotEmpty(remote.authorization)
1204
+ for (const header of remote.authorization) {
1205
+ assert.strictEqual(header, "Bearer secret")
1206
+ }
1207
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1208
+ ),
1209
+ )
1210
+
1211
+ it.live(
1212
+ "resume connects the sent servers, which are never persisted, and close ends them",
1213
+ () =>
1214
+ withStore(
1215
+ Effect.gen(function* () {
1216
+ const fs = yield* FileSystem.FileSystem
1217
+ const path = yield* Path.Path
1218
+ const kvs = yield* KeyValueStore.KeyValueStore
1219
+ const cwd = yield* fs.makeTempDirectoryScoped()
1220
+ const remote = yield* remoteServer("/BROKER-TOKEN")
1221
+ const systems: Array<string> = []
1222
+ const server = yield* makeServer((options) => {
1223
+ systems.push(systemText(options.prompt))
1224
+ return assistantSays("ok")
1225
+ })
1226
+ const prompt = (id: number, sessionId: string) =>
1227
+ server.request(id, "session/prompt", {
1228
+ sessionId,
1229
+ prompt: [{ type: "text", text: "hello" }],
1230
+ })
1231
+
1232
+ const created = yield* server.request(1, "session/new", {
1233
+ cwd,
1234
+ mcpServers: [
1235
+ stdioServer(path, "acpfirst", path.join(cwd, "first.json")),
1236
+ { type: "http", name: "acpbroker", url: remote.url, headers: [] },
1237
+ ],
1238
+ })
1239
+ const sessionId: string = created.result.sessionId
1240
+ yield* prompt(2, sessionId)
1241
+ const first = yield* readStarted(path.join(cwd, "first.json"))
1242
+
1243
+ const closed = yield* server.request(3, "session/close", {
1244
+ sessionId,
1245
+ })
1246
+ assert.isUndefined(closed.error)
1247
+ yield* exited(first.pid)
1248
+ const afterClose = yield* prompt(4, sessionId)
1249
+ assert.isDefined(afterClose.error)
1250
+
1251
+ const persisted = yield* kvs.get(`session-${sessionId}`)
1252
+ assert.isDefined(persisted)
1253
+ assert.notInclude(persisted, "BROKER-TOKEN")
1254
+
1255
+ const resumed = yield* server.request(5, "session/resume", {
1256
+ sessionId,
1257
+ cwd,
1258
+ mcpServers: [
1259
+ stdioServer(path, "acpsecond", path.join(cwd, "second.json")),
1260
+ ],
1261
+ })
1262
+ assert.isUndefined(resumed.error)
1263
+ yield* prompt(6, sessionId)
1264
+ const system = systems.at(-1)!
1265
+ assert.include(system, "acpsecond")
1266
+ assert.notInclude(system, "acpfirst")
1267
+ assert.notInclude(system, "acpbroker")
1268
+
1269
+ const second = yield* readStarted(path.join(cwd, "second.json"))
1270
+ yield* server.request(7, "session/close", { sessionId })
1271
+ yield* exited(second.pid)
1272
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1273
+ ),
1274
+ )
1275
+
1276
+ it.live("starts servers named like Object.prototype members", () =>
1277
+ withStore(
1278
+ Effect.gen(function* () {
1279
+ const fs = yield* FileSystem.FileSystem
1280
+ const path = yield* Path.Path
1281
+ const cwd = yield* fs.makeTempDirectoryScoped()
1282
+ const server = yield* makeServer(() => assistantSays("ok"))
1283
+ const names = ["constructor", "__proto__"]
1284
+ const created = yield* server.request(1, "session/new", {
1285
+ cwd,
1286
+ mcpServers: names.map((name) =>
1287
+ stdioServer(path, name, path.join(cwd, `${name}.json`)),
1288
+ ),
1289
+ })
1290
+ assert.isUndefined(created.error)
1291
+ for (const name of names) {
1292
+ assert.isTrue(
1293
+ yield* fs.exists(path.join(cwd, `${name}.json`)),
1294
+ `${name} was not started`,
1295
+ )
1296
+ }
1297
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1298
+ ),
1299
+ )
952
1300
  })
package/src/Acp.ts CHANGED
@@ -9,17 +9,19 @@
9
9
  * @since 1.0.0
10
10
  */
11
11
  import * as Cause from "effect/Cause"
12
+ import * as Context from "effect/Context"
12
13
  import * as Effect from "effect/Effect"
13
14
  import * as Base64 from "effect/encoding/Base64"
14
15
  import * as Exit from "effect/Exit"
15
16
  import * as Fiber from "effect/Fiber"
16
17
  import * as FileSystem from "effect/FileSystem"
17
- import type * as Layer from "effect/Layer"
18
+ import * as Layer from "effect/Layer"
18
19
  import * as MutableRef from "effect/MutableRef"
19
20
  import * as Option from "effect/Option"
20
21
  import * as Path from "effect/Path"
21
22
  import type * as PlatformError from "effect/PlatformError"
22
23
  import * as Queue from "effect/Queue"
24
+ import * as Redacted from "effect/Redacted"
23
25
  import * as Schema from "effect/Schema"
24
26
  import * as Scope from "effect/Scope"
25
27
  import * as Stdio from "effect/Stdio"
@@ -34,6 +36,7 @@ import * as AgentExecutor from "./AgentExecutor.ts"
34
36
  import type * as AgentOutput from "./AgentOutput.ts"
35
37
  import * as Compaction from "./Compaction.ts"
36
38
  import * as Image from "./Image.ts"
39
+ import * as McpServers from "./McpServers.ts"
37
40
 
38
41
  /**
39
42
  * @since 1.0.0
@@ -153,15 +156,91 @@ const decodeIncoming = Schema.decodeEffect(
153
156
  Schema.fromJsonString(IncomingMessage),
154
157
  )
155
158
 
159
+ const NameValue = Schema.Struct({ name: Schema.String, value: Schema.String })
160
+
161
+ // stdio entries carry no `type`.
162
+ const McpServer = Schema.Union([
163
+ Schema.Struct({
164
+ type: Schema.Literal("http"),
165
+ name: Schema.String,
166
+ url: Schema.String,
167
+ headers: Schema.optionalKey(Schema.Array(NameValue)),
168
+ }),
169
+ Schema.Struct({
170
+ type: Schema.Literal("sse"),
171
+ name: Schema.String,
172
+ }),
173
+ Schema.Struct({
174
+ type: Schema.optionalKey(Schema.Literal("stdio")),
175
+ name: Schema.String,
176
+ command: Schema.String,
177
+ args: Schema.optionalKey(Schema.Array(Schema.String)),
178
+ env: Schema.optionalKey(Schema.Array(NameValue)),
179
+ }),
180
+ ])
181
+
156
182
  const NewSessionParams = Schema.Struct({
157
183
  cwd: Schema.String,
158
184
  model: Schema.optionalKey(Schema.String),
185
+ mcpServers: Schema.optionalKey(Schema.Array(McpServer)),
159
186
  })
160
187
 
161
188
  const LoadSessionParams = Schema.Struct({
162
189
  sessionId: Schema.String,
163
190
  cwd: Schema.optionalKey(Schema.String),
164
191
  model: Schema.optionalKey(Schema.String),
192
+ mcpServers: Schema.optionalKey(Schema.Array(McpServer)),
193
+ })
194
+
195
+ const redactValues = (
196
+ entries: ReadonlyArray<typeof NameValue.Type> | undefined,
197
+ ): Record<string, Redacted.Redacted<string>> =>
198
+ Object.fromEntries(
199
+ (entries ?? []).map(({ name, value }) => [name, Redacted.make(value)]),
200
+ )
201
+
202
+ /**
203
+ * The servers sent with `session/new`, `session/load` or `session/resume`.
204
+ * stdio servers run in the session's cwd; the first of two servers with the
205
+ * same name wins.
206
+ */
207
+ const mcpServerEntries = Effect.fnUntraced(function* (
208
+ servers: ReadonlyArray<typeof McpServer.Type>,
209
+ cwd: string,
210
+ ) {
211
+ const entries: Record<string, McpServers.ServerEntry> = Object.create(null)
212
+ for (const server of servers) {
213
+ if (Object.hasOwn(entries, server.name)) {
214
+ yield* Effect.logWarning("Skipping duplicate MCP server").pipe(
215
+ Effect.annotateLogs({ server: server.name }),
216
+ )
217
+ continue
218
+ }
219
+ switch (server.type) {
220
+ case "http":
221
+ entries[server.name] = {
222
+ type: "http",
223
+ url: server.url,
224
+ headers: redactValues(server.headers),
225
+ }
226
+ break
227
+ case "sse":
228
+ entries[server.name] = {
229
+ type: "unavailable",
230
+ error: "SSE transport is not supported",
231
+ }
232
+ break
233
+ default:
234
+ entries[server.name] = {
235
+ type: "stdio",
236
+ command: server.command,
237
+ args: server.args ?? [],
238
+ env: redactValues(server.env),
239
+ cwd,
240
+ }
241
+ }
242
+ }
243
+ return entries
165
244
  })
166
245
 
167
246
  const SessionIdParams = Schema.Struct({
@@ -304,6 +383,10 @@ interface Session {
304
383
  running: Fiber.Fiber<void, unknown> | undefined
305
384
  toolCalls: number
306
385
  readonly announcedSubagents: Set<number>
386
+ /** Owns the Agent and the session's MCP servers. */
387
+ readonly scope: Scope.Closeable
388
+ /** Failed MCP servers, reported on the first prompt turn. */
389
+ mcpFailures: string | undefined
307
390
  }
308
391
 
309
392
  /**
@@ -335,6 +418,19 @@ export const make = Effect.fnUntraced(function* <RAgent, RModel>(
335
418
  const scope = yield* Effect.scope
336
419
  const sessions = new Map<string, Session>()
337
420
 
421
+ // Whatever ends the server, name the prompts it leaves unfinished. An
422
+ // interrupted prompt keeps its `running` fiber.
423
+ yield* Effect.addFinalizer(() => {
424
+ const running = Array.from(sessions.values())
425
+ .filter((session) => session.running !== undefined)
426
+ .map((session) => session.id)
427
+ return running.length === 0
428
+ ? Effect.void
429
+ : Effect.logWarning("ACP server stopping with prompts in progress").pipe(
430
+ Effect.annotateLogs({ sessions: running.join(", ") }),
431
+ )
432
+ })
433
+
338
434
  const notify = (method: string, params: object) =>
339
435
  options.send({ jsonrpc: "2.0", method, params })
340
436
 
@@ -395,8 +491,31 @@ export const make = Effect.fnUntraced(function* <RAgent, RModel>(
395
491
  const openSession = Effect.fnUntraced(function* (
396
492
  id: string,
397
493
  record: SessionRecord,
494
+ mcpServers: ReadonlyArray<typeof McpServer.Type>,
398
495
  ) {
399
- const agent = yield* Scope.provide(options.makeAgent(record.cwd), scope)
496
+ const sessionScope = yield* Scope.fork(scope)
497
+ let makeAgent = options.makeAgent(record.cwd)
498
+ let mcpFailures: string | undefined
499
+ // Never stored: the servers come with every request that opens the
500
+ // session, and their URLs can carry tokens.
501
+ if (mcpServers.length > 0) {
502
+ const entries = yield* mcpServerEntries(mcpServers, record.cwd)
503
+ const servers = Context.get(
504
+ yield* Layer.buildWithScope(McpServers.layer(entries), sessionScope),
505
+ McpServers.McpServers,
506
+ )
507
+ const failures = Object.entries(yield* servers.status).flatMap(
508
+ ([name, status]) =>
509
+ status._tag === "Failed"
510
+ ? [`MCP server "${name}" failed: ${status.error}`]
511
+ : [],
512
+ )
513
+ if (failures.length > 0) mcpFailures = failures.join("\n")
514
+ makeAgent = makeAgent.pipe(
515
+ Effect.provideService(McpServers.McpServers, servers),
516
+ )
517
+ }
518
+ const agent = yield* Scope.provide(makeAgent, sessionScope)
400
519
  MutableRef.set(agent.history, record.history)
401
520
  if (record.environment !== undefined) {
402
521
  MutableRef.set(agent.environment, record.environment)
@@ -410,6 +529,8 @@ export const make = Effect.fnUntraced(function* <RAgent, RModel>(
410
529
  running: undefined,
411
530
  toolCalls: 0,
412
531
  announcedSubagents: new Set(),
532
+ scope: sessionScope,
533
+ mcpFailures,
413
534
  }
414
535
  sessions.set(id, session)
415
536
  return session
@@ -732,14 +853,18 @@ export const make = Effect.fnUntraced(function* <RAgent, RModel>(
732
853
  agentCapabilities: {
733
854
  loadSession: true,
734
855
  promptCapabilities: { image: true, audio: false, embeddedContext: true },
735
- mcpCapabilities: { http: false, sse: false },
856
+ mcpCapabilities: { http: true, sse: false },
857
+ sessionCapabilities: { close: {} },
736
858
  },
737
859
  authMethods: [],
738
860
  agentInfo: { name: "clanka", version: options.version },
739
861
  })
740
862
 
741
863
  const newSession = Effect.fnUntraced(function* (params: unknown) {
742
- const { cwd, model } = yield* decodeParams(NewSessionParams, params)
864
+ const { cwd, model, mcpServers } = yield* decodeParams(
865
+ NewSessionParams,
866
+ params,
867
+ )
743
868
  const modelId = model ?? options.defaultModel
744
869
  const thoughtLevel = options.defaultThoughtLevel
745
870
  yield* requireModel(modelId, thoughtLevel)
@@ -751,6 +876,7 @@ export const make = Effect.fnUntraced(function* <RAgent, RModel>(
751
876
  thoughtLevel,
752
877
  history: Prompt.empty,
753
878
  }),
879
+ mcpServers ?? [],
754
880
  )
755
881
  yield* persist(session)
756
882
  return { sessionId: session.id, ...sessionState(session) }
@@ -760,7 +886,7 @@ export const make = Effect.fnUntraced(function* <RAgent, RModel>(
760
886
  params: unknown,
761
887
  replay: boolean,
762
888
  ) {
763
- const { sessionId, cwd, model } = yield* decodeParams(
889
+ const { sessionId, cwd, model, mcpServers } = yield* decodeParams(
764
890
  LoadSessionParams,
765
891
  params,
766
892
  )
@@ -793,6 +919,7 @@ export const make = Effect.fnUntraced(function* <RAgent, RModel>(
793
919
  ? { environment: record.value.environment }
794
920
  : {}),
795
921
  }),
922
+ mcpServers ?? [],
796
923
  )
797
924
  if (replay) {
798
925
  yield* replayHistory(session)
@@ -834,6 +961,13 @@ export const make = Effect.fnUntraced(function* <RAgent, RModel>(
834
961
  // Resolve images before the turn starts, so a bad block rejects the
835
962
  // request without a model call.
836
963
  const input = yield* promptFromBlocks(session.cwd, prompt)
964
+ if (session.mcpFailures !== undefined) {
965
+ yield* update(sessionId, {
966
+ sessionUpdate: "agent_thought_chunk",
967
+ content: textContent(session.mcpFailures),
968
+ })
969
+ session.mcpFailures = undefined
970
+ }
837
971
  session.running = yield* runTurn(session, input).pipe(
838
972
  Effect.provide(model),
839
973
  Effect.scoped,
@@ -847,6 +981,19 @@ export const make = Effect.fnUntraced(function* <RAgent, RModel>(
847
981
  return yield* toRpcError(exit.cause)
848
982
  })
849
983
 
984
+ // Ends the session in this process: its prompt, Agent and MCP servers. It
985
+ // can be loaded again from the store.
986
+ const closeSession = Effect.fnUntraced(function* (params: unknown) {
987
+ const { sessionId } = yield* decodeParams(SessionIdParams, params)
988
+ const session = yield* getSession(sessionId)
989
+ sessions.delete(sessionId)
990
+ if (session.running !== undefined) {
991
+ yield* Fiber.interrupt(session.running)
992
+ }
993
+ yield* Scope.close(session.scope, Exit.void)
994
+ return {}
995
+ })
996
+
850
997
  const cancel = Effect.fnUntraced(function* (params: unknown) {
851
998
  const { sessionId } = yield* decodeParams(SessionIdParams, params)
852
999
  const running = sessions.get(sessionId)?.running
@@ -873,6 +1020,8 @@ export const make = Effect.fnUntraced(function* <RAgent, RModel>(
873
1020
  return loadSession(params, true)
874
1021
  case "session/resume":
875
1022
  return loadSession(params, false)
1023
+ case "session/close":
1024
+ return closeSession(params)
876
1025
  case "session/set_model":
877
1026
  return setModel(params)
878
1027
  case "session/prompt":