typeclaw 0.42.0 → 0.43.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.
Files changed (89) hide show
  1. package/auth.schema.json +16 -0
  2. package/package.json +3 -3
  3. package/secrets.schema.json +16 -0
  4. package/src/agent/adaptive-thinking-compat.ts +79 -0
  5. package/src/agent/index.ts +79 -101
  6. package/src/agent/live-subagents.ts +4 -4
  7. package/src/agent/plugin-tools.ts +85 -132
  8. package/src/agent/provider-error.ts +37 -0
  9. package/src/agent/reload-tool.ts +1 -1
  10. package/src/agent/session-origin.ts +6 -3
  11. package/src/agent/subagents.ts +2 -2
  12. package/src/agent/system-prompt.ts +24 -8
  13. package/src/agent/tool-result-budget.ts +1 -1
  14. package/src/agent/tools/channel-react.ts +5 -4
  15. package/src/agent/tools/spawn-subagent.ts +80 -24
  16. package/src/agent/tools/stream-snapshot.ts +8 -3
  17. package/src/bundled-plugins/agent-browser/index.ts +18 -8
  18. package/src/bundled-plugins/memory/README.md +4 -1
  19. package/src/bundled-plugins/memory/belief-sentence.ts +50 -0
  20. package/src/bundled-plugins/memory/dreaming.ts +13 -6
  21. package/src/bundled-plugins/memory/load-memory.ts +22 -2
  22. package/src/bundled-plugins/memory/memory-logger.ts +1 -1
  23. package/src/bundled-plugins/planner/planner.ts +1 -1
  24. package/src/bundled-plugins/researcher/researcher.ts +2 -2
  25. package/src/bundled-plugins/reviewer/reviewer.ts +1 -1
  26. package/src/capabilities/control-plane.ts +24 -0
  27. package/src/capabilities/index.ts +2 -0
  28. package/src/capabilities/runtime.ts +30 -0
  29. package/src/channels/adapters/discord-bot-thread-room.ts +73 -0
  30. package/src/channels/adapters/discord-bot.ts +9 -1
  31. package/src/channels/adapters/slack-bot-classify.ts +1 -0
  32. package/src/channels/adapters/slack-classify.ts +1 -0
  33. package/src/channels/engagement.ts +33 -0
  34. package/src/channels/manager.ts +41 -47
  35. package/src/channels/router.ts +150 -21
  36. package/src/channels/types.ts +10 -0
  37. package/src/cli/channel.ts +49 -12
  38. package/src/cli/command-meta.ts +2 -0
  39. package/src/cli/hostd.ts +4 -3
  40. package/src/cli/index.ts +1 -0
  41. package/src/cli/logs.ts +2 -2
  42. package/src/cli/mcp.ts +233 -0
  43. package/src/cli/restart.ts +5 -3
  44. package/src/cli/shell.ts +2 -2
  45. package/src/cli/start.ts +2 -2
  46. package/src/cli/status.ts +2 -2
  47. package/src/cli/stop.ts +2 -2
  48. package/src/compose/restart.ts +4 -3
  49. package/src/compose/start.ts +2 -2
  50. package/src/compose/stop.ts +2 -2
  51. package/src/config/config.ts +10 -1
  52. package/src/config/providers.ts +61 -9
  53. package/src/container/controller.ts +104 -0
  54. package/src/container/index.ts +9 -0
  55. package/src/hostd/daemon.ts +28 -9
  56. package/src/hostd/protocol.ts +12 -9
  57. package/src/init/index.ts +1 -1
  58. package/src/init/instagram-auth.ts +189 -34
  59. package/src/inspect/logs-item.ts +2 -2
  60. package/src/mcp/client.ts +16 -6
  61. package/src/mcp/index.ts +12 -0
  62. package/src/mcp/manager.ts +9 -4
  63. package/src/mcp/oauth.ts +212 -0
  64. package/src/run/index.ts +36 -11
  65. package/src/run/{codex-fetch-observer.ts → llm-fetch-observer.ts} +182 -82
  66. package/src/sandbox/availability.ts +2 -2
  67. package/src/sandbox/build.ts +1 -1
  68. package/src/sandbox/hidden-paths.ts +59 -0
  69. package/src/sandbox/index.ts +1 -1
  70. package/src/sandbox/policy.ts +2 -2
  71. package/src/secrets/discord-store.ts +4 -13
  72. package/src/secrets/index.ts +1 -1
  73. package/src/secrets/instagram-store.ts +4 -13
  74. package/src/secrets/kakao-store.ts +4 -13
  75. package/src/secrets/line-store.ts +4 -13
  76. package/src/secrets/schema.ts +13 -0
  77. package/src/secrets/secrets-provider.ts +86 -0
  78. package/src/secrets/slack-store.ts +4 -13
  79. package/src/secrets/storage.ts +108 -1
  80. package/src/secrets/webex-store.ts +4 -13
  81. package/src/server/index.ts +2 -2
  82. package/src/skills/typeclaw-channel-github/SKILL.md +2 -2
  83. package/src/skills/typeclaw-channel-instagram/SKILL.md +1 -1
  84. package/src/skills/typeclaw-config/SKILL.md +5 -3
  85. package/src/skills/typeclaw-plugins/SKILL.md +1 -1
  86. package/src/skills/typeclaw-troubleshooting/SKILL.md +1 -1
  87. package/src/stream/broker.ts +4 -3
  88. package/src/stream/types.ts +1 -0
  89. package/typeclaw.schema.json +14 -0
@@ -11,6 +11,7 @@ import {
11
11
  instagramChannelBlockSchema,
12
12
  kakaoChannelBlockSchema,
13
13
  lineChannelBlockSchema,
14
+ mcpCredentialSchema,
14
15
  slackChannelBlockSchema,
15
16
  webexChannelBlockSchema,
16
17
  } from '@/secrets/schema'
@@ -527,19 +528,37 @@ export async function startDaemon(opts: DaemonOptions = {}): Promise<Daemon> {
527
528
 
528
529
  const handleSecretsPatch = async (req: {
529
530
  containerName: string
530
- patch: {
531
- channels:
532
- | { kakaotalk: unknown }
533
- | { discord: unknown }
534
- | { instagram: unknown }
535
- | { line: unknown }
536
- | { webex: unknown }
537
- | { slack: unknown }
538
- }
531
+ patch:
532
+ | {
533
+ channels:
534
+ | { kakaotalk: unknown }
535
+ | { discord: unknown }
536
+ | { instagram: unknown }
537
+ | { line: unknown }
538
+ | { webex: unknown }
539
+ | { slack: unknown }
540
+ mcp?: never
541
+ }
542
+ | { mcp: { server: unknown; credential: unknown }; channels?: never }
539
543
  }): Promise<RpcResponse> =>
540
544
  runSerially(req.containerName, async () => {
541
545
  const cwd = cwds.get(req.containerName)
542
546
  if (!cwd) return { ok: false, reason: `not registered: ${req.containerName}` }
547
+ if (req.patch.mcp !== undefined) {
548
+ const server = req.patch.mcp.server
549
+ if (typeof server !== 'string' || server.length === 0) return { ok: false, reason: 'mcp.server is required' }
550
+ const parsed = mcpCredentialSchema.safeParse(req.patch.mcp.credential)
551
+ if (!parsed.success) {
552
+ return { ok: false, reason: parsed.error.issues.map((issue) => issue.message).join('; ') }
553
+ }
554
+ const backend = new SecretsBackend(join(cwd, 'secrets.json'))
555
+ await backend.updateMcpAsync(async (mcp) => ({
556
+ result: undefined,
557
+ next: { ...mcp, [server]: parsed.data },
558
+ }))
559
+ const result: SecretsPatchResult = { containerName: req.containerName, patched: true }
560
+ return { ok: true, result }
561
+ }
543
562
  const channelsPatch = req.patch?.channels
544
563
  // Exactly one personal-account channel block per patch. KakaoTalk, LINE,
545
564
  // and Webex write their structured account block through this RPC; the
@@ -4,10 +4,21 @@ import type {
4
4
  InstagramChannelBlock,
5
5
  KakaoChannelBlock,
6
6
  LineChannelBlock,
7
+ McpCredential,
7
8
  SlackChannelBlock,
8
9
  WebexChannelBlock,
9
10
  } from '@/secrets/schema'
10
11
 
12
+ export type SecretsPatchChannels =
13
+ | { kakaotalk: KakaoChannelBlock }
14
+ | { discord: DiscordChannelBlock }
15
+ | { instagram: InstagramChannelBlock }
16
+ | { line: LineChannelBlock }
17
+ | { webex: WebexChannelBlock }
18
+ | { slack: SlackChannelBlock }
19
+
20
+ export type SecretsPatchMcp = { server: string; credential: McpCredential }
21
+
11
22
  export type Request =
12
23
  | {
13
24
  kind: 'register'
@@ -25,15 +36,7 @@ export type Request =
25
36
  | {
26
37
  kind: 'secrets-patch'
27
38
  containerName: string
28
- patch: {
29
- channels:
30
- | { kakaotalk: KakaoChannelBlock }
31
- | { discord: DiscordChannelBlock }
32
- | { instagram: InstagramChannelBlock }
33
- | { line: LineChannelBlock }
34
- | { webex: WebexChannelBlock }
35
- | { slack: SlackChannelBlock }
36
- }
39
+ patch: { channels: SecretsPatchChannels; mcp?: never } | { mcp: SecretsPatchMcp; channels?: never }
37
40
  }
38
41
  | { kind: 'http-info' }
39
42
  | { kind: 'version' }
package/src/init/index.ts CHANGED
@@ -373,7 +373,7 @@ export async function runInit({
373
373
  })
374
374
  // Only write the LLM API key on the api-key path. OAuth providers persist
375
375
  // their credentials to secrets.json (via the OAuth login step above); writing
376
- // an empty FIREWORKS_API_KEY/OPENAI_API_KEY would just confuse users.
376
+ // an empty OPENAI_API_KEY would just confuse users.
377
377
  await writeSecrets(cwd, {
378
378
  model,
379
379
  apiKey: resolvedAuth.kind === 'api-key' ? resolvedAuth.apiKey : undefined,
@@ -1,3 +1,4 @@
1
+ import { readFile, rm, writeFile } from 'node:fs/promises'
1
2
  import { join } from 'node:path'
2
3
 
3
4
  import {
@@ -11,10 +12,31 @@ import { SecretsInstagramCredentialStore } from '@/secrets/instagram-store'
11
12
 
12
13
  export type InstagramBootstrapStatus = { ok: true } | { ok: false; reason: string }
13
14
 
15
+ // Instagram gates a fresh login behind one of two interactive second factors:
16
+ // a 2FA code (authenticator app / SMS the account already has enabled) or a
17
+ // checkpoint challenge (a suspicious-login verification code sent to email or
18
+ // SMS). Both require a human to read a code off a device, so they only work
19
+ // with a TTY. The callbacks return the entered code, or `null` when the user
20
+ // aborts / no interactive prompt is available (cron/container re-auth) — in
21
+ // which case the bootstrap fails loudly instead of hanging.
22
+ export type InstagramLoginCallbacks = {
23
+ onTwoFactorCode?: (info: InstagramTwoFactorPrompt) => Promise<string | null>
24
+ onChallengeCode?: (info: InstagramChallengePrompt) => Promise<InstagramChallengeResponse | null>
25
+ }
26
+
27
+ export type InstagramTwoFactorPrompt = { username: string }
28
+
29
+ export type InstagramChallengePrompt = { contactPoint: string; method: InstagramChallengeMethod }
30
+
31
+ export type InstagramChallengeMethod = 'email' | 'sms'
32
+
33
+ export type InstagramChallengeResponse = { code: string }
34
+
14
35
  export type InstagramLoginInput = {
15
36
  username: string
16
37
  password: string
17
38
  agentDir: string
39
+ callbacks?: InstagramLoginCallbacks
18
40
  client?: InstagramLoginClient
19
41
  credentialManager?: InstagramLoginCredentialManager
20
42
  }
@@ -27,8 +49,20 @@ export type InstagramAuthenticateResult = {
27
49
  challengePath?: string
28
50
  }
29
51
 
52
+ export type InstagramTwoFactorResult = { userId: string }
53
+
54
+ export type InstagramChallengeSendResult = { contactPoint: string; stepName: string }
55
+
56
+ export type InstagramChallengeSubmitResult = { userId: string }
57
+
58
+ // Structural subset of the upstream InstagramClient the bootstrap drives.
59
+ // Declared here (rather than relying on the SDK class) so tests can inject a
60
+ // fake without standing up the real HTTP client, mirroring the LINE adapter.
30
61
  export type InstagramLoginClient = {
31
62
  authenticate(username: string, password: string): Promise<InstagramAuthenticateResult>
63
+ twoFactorLogin(username: string, code: string, twoFactorIdentifier: string): Promise<InstagramTwoFactorResult>
64
+ challengeSendCode(apiPath: string, method?: InstagramChallengeMethod): Promise<InstagramChallengeSendResult>
65
+ challengeSubmitCode(apiPath: string, code: string): Promise<InstagramChallengeSubmitResult>
32
66
  setSessionPath(path: string): void
33
67
  getUserId(): string | null
34
68
  }
@@ -63,37 +97,23 @@ export async function runInstagramBootstrap(input: InstagramLoginInput): Promise
63
97
  const paths = await manager.ensureAccountPaths(accountId)
64
98
  const client = input.client ?? buildInstagramClient(sdkManager)
65
99
  client.setSessionPath(paths.session_path)
66
- const auth = await client.authenticate(input.username, input.password)
67
- if (auth.requiresTwoFactor) return unsupportedTwoFactor()
68
- if (auth.challengeRequired) return unsupportedChallenge()
69
- const userId = auth.userId || client.getUserId()
70
- if (userId === null || userId === '') return { ok: false, reason: 'Instagram login did not authenticate' }
71
-
72
- const now = new Date().toISOString()
73
- await manager.setAccount({
74
- account_id: accountId,
75
- username: input.username,
76
- pk: userId,
77
- created_at: now,
78
- updated_at: now,
79
- })
80
- await manager.setCurrent(accountId)
81
-
82
- const sdkAccount = await manager.getAccount(accountId)
83
- if (sdkAccount === null) {
84
- return { ok: false, reason: 'Instagram login authenticated but did not persist SDK credentials' }
100
+
101
+ // A checkpoint login persists a partial SDK session (challenge_path +
102
+ // cookies) inside authenticate(), before we know whether the operator
103
+ // can finish it. Snapshot the file up front and restore it on any
104
+ // failure — whether completeLogin returns a non-ok status (fail-closed
105
+ // / cancelled) or throws (e.g. challengeSubmitCode rejecting a wrong
106
+ // code) — so a half-written session is never left behind. Rethrow so
107
+ // the outer catch reports the error.
108
+ const sessionSnapshot = await snapshotSessionFile(paths.session_path)
109
+ try {
110
+ const result = await completeLogin({ store, manager, client, accountId, input })
111
+ if (!result.ok) await restoreSessionFile(paths.session_path, sessionSnapshot)
112
+ return result
113
+ } catch (err) {
114
+ await restoreSessionFile(paths.session_path, sessionSnapshot)
115
+ throw err
85
116
  }
86
- await store.setAccount({
87
- account_id: sdkAccount.account_id,
88
- username: sdkAccount.username,
89
- ...(sdkAccount.full_name !== undefined ? { full_name: sdkAccount.full_name } : {}),
90
- ...(sdkAccount.profile_pic_url !== undefined ? { profile_pic_url: sdkAccount.profile_pic_url } : {}),
91
- ...(sdkAccount.pk !== undefined ? { pk: sdkAccount.pk } : {}),
92
- created_at: sdkAccount.created_at,
93
- updated_at: sdkAccount.updated_at,
94
- })
95
- await store.setCurrentAccount(sdkAccount.account_id)
96
- return { ok: true }
97
117
  },
98
118
  )
99
119
  return result
@@ -102,23 +122,158 @@ export async function runInstagramBootstrap(input: InstagramLoginInput): Promise
102
122
  }
103
123
  }
104
124
 
125
+ type ResolvedUserId = { ok: true; userId: string } | { ok: false; reason: string }
126
+
127
+ async function completeLogin(args: {
128
+ store: SecretsInstagramCredentialStore
129
+ manager: InstagramLoginCredentialManager
130
+ client: InstagramLoginClient
131
+ accountId: string
132
+ input: InstagramLoginInput
133
+ }): Promise<InstagramBootstrapStatus> {
134
+ const { store, manager, client, accountId, input } = args
135
+ const resolved = await resolveUserId(client, input)
136
+ if (!resolved.ok) return resolved
137
+ const userId = resolved.userId || client.getUserId()
138
+ if (userId === null || userId === '') return { ok: false, reason: 'Instagram login did not authenticate' }
139
+ return persistAccount({ store, manager, accountId, username: input.username, userId })
140
+ }
141
+
142
+ // Drives the authenticate → (optional 2FA / challenge) → userId path. Each
143
+ // second factor is completed in place so a successful code entry continues to
144
+ // the same persist step a clean login would, and an aborted / unsupported
145
+ // prompt fails loudly rather than leaving a half-written session.
146
+ async function resolveUserId(client: InstagramLoginClient, input: InstagramLoginInput): Promise<ResolvedUserId> {
147
+ const auth = await client.authenticate(input.username, input.password)
148
+ if (auth.requiresTwoFactor) return completeTwoFactor(client, input, auth)
149
+ if (auth.challengeRequired) return completeChallenge(client, input, auth)
150
+ return { ok: true, userId: auth.userId }
151
+ }
152
+
153
+ async function completeTwoFactor(
154
+ client: InstagramLoginClient,
155
+ input: InstagramLoginInput,
156
+ auth: InstagramAuthenticateResult,
157
+ ): Promise<ResolvedUserId> {
158
+ const identifier = readTwoFactorIdentifier(auth.twoFactorInfo)
159
+ if (identifier === null) {
160
+ return { ok: false, reason: 'Instagram requested 2FA but did not return a two-factor identifier.' }
161
+ }
162
+ const prompt = input.callbacks?.onTwoFactorCode
163
+ if (prompt === undefined) return twoFactorUnavailable()
164
+ const code = await prompt({ username: input.username })
165
+ if (code === null || code.trim() === '') {
166
+ return { ok: false, reason: 'Instagram 2FA was cancelled — no verification code was entered.' }
167
+ }
168
+ const result = await client.twoFactorLogin(input.username, code.trim(), identifier)
169
+ return { ok: true, userId: result.userId }
170
+ }
171
+
172
+ async function completeChallenge(
173
+ client: InstagramLoginClient,
174
+ input: InstagramLoginInput,
175
+ auth: InstagramAuthenticateResult,
176
+ ): Promise<ResolvedUserId> {
177
+ const path = auth.challengePath
178
+ if (path === undefined || path === '') {
179
+ return { ok: false, reason: 'Instagram requested a checkpoint but did not return a challenge path.' }
180
+ }
181
+ const prompt = input.callbacks?.onChallengeCode
182
+ if (prompt === undefined) return challengeUnavailable()
183
+
184
+ // Instagram sends the verification code to email by default; SMS is only an
185
+ // option when the account has a verified phone. Send-then-prompt keeps the
186
+ // code delivery inside the interactive window so a stale contact point can't
187
+ // leave the user waiting on a code that was never dispatched.
188
+ const method: InstagramChallengeMethod = 'email'
189
+ const sent = await client.challengeSendCode(path, method)
190
+ const response = await prompt({ contactPoint: sent.contactPoint, method })
191
+ if (response === null || response.code.trim() === '') {
192
+ return { ok: false, reason: 'Instagram checkpoint was cancelled — no verification code was entered.' }
193
+ }
194
+ const result = await client.challengeSubmitCode(path, response.code.trim())
195
+ return { ok: true, userId: result.userId }
196
+ }
197
+
198
+ async function persistAccount(args: {
199
+ store: SecretsInstagramCredentialStore
200
+ manager: InstagramLoginCredentialManager
201
+ accountId: string
202
+ username: string
203
+ userId: string
204
+ }): Promise<InstagramBootstrapStatus> {
205
+ const { store, manager, accountId, username, userId } = args
206
+ const now = new Date().toISOString()
207
+ await manager.setAccount({
208
+ account_id: accountId,
209
+ username,
210
+ pk: userId,
211
+ created_at: now,
212
+ updated_at: now,
213
+ })
214
+ await manager.setCurrent(accountId)
215
+
216
+ const sdkAccount = await manager.getAccount(accountId)
217
+ if (sdkAccount === null) {
218
+ return { ok: false, reason: 'Instagram login authenticated but did not persist SDK credentials' }
219
+ }
220
+ await store.setAccount({
221
+ account_id: sdkAccount.account_id,
222
+ username: sdkAccount.username,
223
+ ...(sdkAccount.full_name !== undefined ? { full_name: sdkAccount.full_name } : {}),
224
+ ...(sdkAccount.profile_pic_url !== undefined ? { profile_pic_url: sdkAccount.profile_pic_url } : {}),
225
+ ...(sdkAccount.pk !== undefined ? { pk: sdkAccount.pk } : {}),
226
+ created_at: sdkAccount.created_at,
227
+ updated_at: sdkAccount.updated_at,
228
+ })
229
+ await store.setCurrentAccount(sdkAccount.account_id)
230
+ return { ok: true }
231
+ }
232
+
233
+ // The SDK returns `two_factor_info.two_factor_identifier`; it's the opaque
234
+ // token `twoFactorLogin` must echo back. Read defensively — a shape drift
235
+ // surfaces as a clear error instead of an SDK-internal crash.
236
+ function readTwoFactorIdentifier(info: Record<string, unknown> | undefined): string | null {
237
+ const identifier = info?.['two_factor_identifier']
238
+ return typeof identifier === 'string' && identifier !== '' ? identifier : null
239
+ }
240
+
241
+ async function snapshotSessionFile(path: string): Promise<string | null> {
242
+ try {
243
+ return await readFile(path, 'utf8')
244
+ } catch {
245
+ return null
246
+ }
247
+ }
248
+
249
+ // Restore the pre-login state: rewrite the prior contents, or delete the file
250
+ // when no session existed before, so a failed second factor leaves the session
251
+ // path exactly as it was found.
252
+ async function restoreSessionFile(path: string, snapshot: string | null): Promise<void> {
253
+ if (snapshot === null) {
254
+ await rm(path, { force: true })
255
+ return
256
+ }
257
+ await writeFile(path, snapshot, { mode: 0o600 })
258
+ }
259
+
105
260
  function buildInstagramClient(manager: InstagramCredentialManager): InstagramLoginClient {
106
261
  return new RealInstagramClient(manager) as unknown as InstagramLoginClient
107
262
  }
108
263
 
109
- function unsupportedTwoFactor(): InstagramBootstrapStatus {
264
+ function twoFactorUnavailable(): { ok: false; reason: string } {
110
265
  return {
111
266
  ok: false,
112
267
  reason:
113
- 'Instagram account requires 2FA/checkpoint, which is not yet supported by the typeclaw Instagram channel. Disable 2FA on a dedicated agent account, or complete the checkpoint in a browser first.',
268
+ 'Instagram account requires a 2FA code, but no interactive prompt is available. Run `typeclaw channel add instagram` (or `typeclaw channel reauth instagram`) from a terminal to enter the code.',
114
269
  }
115
270
  }
116
271
 
117
- function unsupportedChallenge(): InstagramBootstrapStatus {
272
+ function challengeUnavailable(): { ok: false; reason: string } {
118
273
  return {
119
274
  ok: false,
120
275
  reason:
121
- 'Instagram account requires 2FA/checkpoint, which is not yet supported by the typeclaw Instagram channel. Disable 2FA on a dedicated agent account, or complete the checkpoint in a browser first.',
276
+ 'Instagram account requires a checkpoint verification code, but no interactive prompt is available. Run `typeclaw channel add instagram` (or `typeclaw channel reauth instagram`) from a terminal to enter the code.',
122
277
  }
123
278
  }
124
279
 
@@ -1,4 +1,4 @@
1
- import { logs } from '@/container'
1
+ import { resolveController } from '@/container'
2
2
 
3
3
  export type StreamLogsOptions = {
4
4
  cwd: string
@@ -28,7 +28,7 @@ export async function streamLogs(opts: StreamLogsOptions): Promise<StreamLogsRes
28
28
  const out = lineSink(opts.stdout)
29
29
  const err = lineSink(opts.stderr)
30
30
 
31
- const result = await logs({
31
+ const result = await resolveController().logs({
32
32
  cwd: opts.cwd,
33
33
  follow: true,
34
34
  out,
package/src/mcp/client.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js'
1
2
  import { Client } from '@modelcontextprotocol/sdk/client/index.js'
2
3
  import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'
3
4
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
@@ -55,12 +56,13 @@ export async function connectMcpServer(
55
56
  connectTimeoutMs?: number
56
57
  client?: McpConnectClient
57
58
  transport?: Transport
59
+ authProvider?: OAuthClientProvider
58
60
  },
59
61
  ): Promise<McpConnection> {
60
62
  const requestTimeout = server.timeoutMs ?? DEFAULT_MCP_REQUEST_TIMEOUT_MS
61
63
  const connectTimeout = opts.connectTimeoutMs ?? DEFAULT_MCP_CONNECT_TIMEOUT_MS
62
64
  const client = opts.client ?? new Client({ name: 'typeclaw', version: '0.17.0' }, { capabilities: {} })
63
- const transport = opts.transport ?? createTransport(server, opts.env)
65
+ const transport = opts.transport ?? createTransport(server, opts.env, opts.authProvider)
64
66
 
65
67
  try {
66
68
  await withConnectDeadline(connectTimeout, opts.signal, (signal) =>
@@ -141,10 +143,18 @@ export function createMcpConnection(
141
143
  }
142
144
  }
143
145
 
144
- function createTransport(server: McpServer, env: NodeJS.ProcessEnv): Transport {
145
- return server.command
146
- ? new StdioClientTransport({ command: server.command, args: server.args, env: resolveServerEnv(server, env) })
147
- : new StreamableHTTPClientTransport(new URL(requiredUrl(server)))
146
+ export function createTransport(
147
+ server: McpServer,
148
+ env: NodeJS.ProcessEnv,
149
+ authProvider?: OAuthClientProvider,
150
+ ): Transport {
151
+ if (server.command) {
152
+ return new StdioClientTransport({ command: server.command, args: server.args, env: resolveServerEnv(server, env) })
153
+ }
154
+ const url = new URL(requiredUrl(server))
155
+ return authProvider === undefined
156
+ ? new StreamableHTTPClientTransport(url)
157
+ : new StreamableHTTPClientTransport(url, { authProvider })
148
158
  }
149
159
 
150
160
  async function withConnectDeadline<T>(
@@ -206,7 +216,7 @@ function attachCloseCause(cause: unknown, closeCause: unknown): void {
206
216
 
207
217
  // A stdio MCP server is a child process the agent spawns, so it must NOT
208
218
  // inherit the full parent environment: that env holds unrelated credentials
209
- // (FIREWORKS_API_KEY, GH_TOKEN, channel tokens) and inheriting them leaks every
219
+ // (OPENAI_API_KEY, GH_TOKEN, channel tokens) and inheriting them leaks every
210
220
  // secret to every server. We start from a minimal allowlist needed to spawn and
211
221
  // run a process (PATH/HOME to launch npx/bunx, locale + temp for correctness),
212
222
  // then overlay only the secrets the server explicitly declares. This mirrors
package/src/mcp/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export {
2
2
  connectMcpServer,
3
3
  createMcpConnection,
4
+ createTransport,
4
5
  resolveServerEnv,
5
6
  type McpConnection,
6
7
  type McpSdkClient,
@@ -14,6 +15,17 @@ export {
14
15
  type McpConnectResult,
15
16
  type McpManager,
16
17
  } from './manager'
18
+ export {
19
+ createFileMcpOAuthStore,
20
+ createHostdMcpOAuthStore,
21
+ listMcpCredentials,
22
+ resolveContainerMcpOAuthStore,
23
+ TypeClawMcpOAuthProvider,
24
+ type HostdMcpOAuthStoreOptions,
25
+ type McpOAuthInvalidateScope,
26
+ type McpOAuthStore,
27
+ type TypeClawMcpOAuthProviderOptions,
28
+ } from './oauth'
17
29
  export { renderMcpCatalog, type McpCatalogServer } from './catalog'
18
30
  export {
19
31
  createMcpDispatcherTools,
@@ -1,3 +1,5 @@
1
+ import type { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js'
2
+
1
3
  import type { McpServer } from '@/config/config'
2
4
 
3
5
  import { connectMcpServer, type McpConnection } from './client'
@@ -22,12 +24,14 @@ export type McpManager = {
22
24
 
23
25
  export type ConnectMcpServerFn = (
24
26
  server: McpServer,
25
- opts: { env: NodeJS.ProcessEnv; signal?: AbortSignal },
27
+ opts: { env: NodeJS.ProcessEnv; signal?: AbortSignal; authProvider?: OAuthClientProvider },
26
28
  ) => Promise<McpConnection>
27
29
 
30
+ export type McpAuthProviderFactory = (server: McpServer) => OAuthClientProvider | undefined
31
+
28
32
  export function createMcpManager(
29
33
  servers: McpServer[],
30
- opts: { env: NodeJS.ProcessEnv; connect?: ConnectMcpServerFn },
34
+ opts: { env: NodeJS.ProcessEnv; connect?: ConnectMcpServerFn; authProvider?: McpAuthProviderFactory },
31
35
  ): McpManager {
32
36
  const activeServers = servers.filter((server) => server.enabled)
33
37
  const connect = opts.connect ?? connectMcpServer
@@ -62,7 +66,7 @@ export function createMcpManager(
62
66
  const pending = inflight.get(server.name)
63
67
  if (pending !== undefined) return pending
64
68
 
65
- const attempt = connectOne(server, opts.env, connect, signal).then(async (result) => {
69
+ const attempt = connectOne(server, opts.env, connect, signal, opts.authProvider?.(server)).then(async (result) => {
66
70
  inflight.delete(server.name)
67
71
  if (result.ok) {
68
72
  if (closed) {
@@ -207,10 +211,11 @@ async function connectOne(
207
211
  env: NodeJS.ProcessEnv,
208
212
  connect: ConnectMcpServerFn,
209
213
  signal: AbortSignal | undefined,
214
+ authProvider: OAuthClientProvider | undefined,
210
215
  ): Promise<McpConnectResult> {
211
216
  let connection: McpConnection | undefined
212
217
  try {
213
- connection = await connect(server, { env, signal })
218
+ connection = await connect(server, { env, signal, authProvider })
214
219
  const tools = await connection.listTools()
215
220
  return { ok: true, name: server.name, connection, toolCount: tools.length }
216
221
  } catch (cause) {