typeclaw 0.42.1 → 0.43.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/auth.schema.json +16 -0
- package/package.json +2 -2
- package/secrets.schema.json +16 -0
- package/src/agent/index.ts +9 -2
- package/src/agent/live-subagents.ts +4 -4
- package/src/agent/plugin-tools.ts +8 -2
- package/src/agent/session-origin.ts +6 -3
- package/src/agent/system-prompt.ts +41 -3
- package/src/agent/tools/channel-react.ts +5 -4
- package/src/agent/tools/spawn-subagent.ts +80 -24
- package/src/bundled-plugins/planner/planner.ts +1 -1
- package/src/bundled-plugins/researcher/researcher.ts +2 -2
- package/src/bundled-plugins/reviewer/reviewer.ts +1 -1
- package/src/channels/adapters/discord-bot-thread-room.ts +73 -0
- package/src/channels/adapters/discord-bot.ts +85 -4
- package/src/channels/adapters/discord.ts +15 -2
- package/src/channels/adapters/slack-bot-classify.ts +1 -0
- package/src/channels/adapters/slack-classify.ts +1 -0
- package/src/channels/engagement.ts +33 -0
- package/src/channels/manager.ts +9 -1
- package/src/channels/router.ts +500 -91
- package/src/channels/schema.ts +24 -0
- package/src/channels/types.ts +18 -5
- package/src/cli/channel.ts +40 -13
- package/src/cli/command-meta.ts +2 -0
- package/src/cli/index.ts +1 -0
- package/src/cli/mcp.ts +233 -0
- package/src/hostd/daemon.ts +28 -9
- package/src/hostd/protocol.ts +12 -9
- package/src/mcp/client.ts +15 -5
- package/src/mcp/index.ts +12 -0
- package/src/mcp/manager.ts +9 -4
- package/src/mcp/oauth.ts +212 -0
- package/src/run/index.ts +15 -2
- package/src/sandbox/hidden-paths.ts +59 -0
- package/src/sandbox/index.ts +1 -1
- package/src/secrets/index.ts +1 -1
- package/src/secrets/schema.ts +13 -0
- package/src/secrets/secrets-provider.ts +2 -2
- package/src/secrets/storage.ts +108 -1
- package/src/skills/typeclaw-channel-github/SKILL.md +2 -2
- package/src/skills/typeclaw-troubleshooting/SKILL.md +1 -1
package/src/channels/schema.ts
CHANGED
|
@@ -16,6 +16,30 @@ export const ADAPTER_IDS = [
|
|
|
16
16
|
|
|
17
17
|
export type AdapterId = (typeof ADAPTER_IDS)[number]
|
|
18
18
|
|
|
19
|
+
export type ReadCapability = 'history' | 'message-get' | 'list'
|
|
20
|
+
|
|
21
|
+
// Which arbitrary-read callbacks each adapter registers when it starts healthy.
|
|
22
|
+
// A missing callback means "adapter-unavailable" (failed to start) ONLY for a
|
|
23
|
+
// capability listed here; capabilities an adapter never implements stay
|
|
24
|
+
// "not-supported" even when the adapter is configured and running. Kept as a
|
|
25
|
+
// static table because the distinction must survive a failed start() (which
|
|
26
|
+
// registers nothing), so it can't be derived from the live callback registry.
|
|
27
|
+
// The guard test in schema.test.ts asserts this matches what each adapter's
|
|
28
|
+
// start() actually registers — update both together or CI fails.
|
|
29
|
+
export const ADAPTER_READ_CAPABILITIES: Record<AdapterId, readonly ReadCapability[]> = {
|
|
30
|
+
discord: ['history'],
|
|
31
|
+
'discord-bot': ['history', 'message-get', 'list'],
|
|
32
|
+
github: ['history'],
|
|
33
|
+
instagram: ['history'],
|
|
34
|
+
line: ['history'],
|
|
35
|
+
kakaotalk: ['history'],
|
|
36
|
+
slack: ['history'],
|
|
37
|
+
'slack-bot': ['history', 'message-get', 'list'],
|
|
38
|
+
'telegram-bot': [],
|
|
39
|
+
webex: ['history'],
|
|
40
|
+
'webex-bot': ['history'],
|
|
41
|
+
}
|
|
42
|
+
|
|
19
43
|
const engagementTriggerSchema = z.enum(['mention', 'reply', 'dm'])
|
|
20
44
|
|
|
21
45
|
const stickinessSchema = z.union([
|
package/src/channels/types.ts
CHANGED
|
@@ -51,6 +51,16 @@ export type InboundMessage = {
|
|
|
51
51
|
workspace: string
|
|
52
52
|
chat: string
|
|
53
53
|
thread: string | null
|
|
54
|
+
// Structural "this message lives in a thread room" signal, kept SEPARATE
|
|
55
|
+
// from `thread`. `thread` is a reply-routing field whose meaning differs per
|
|
56
|
+
// platform: Slack puts the thread ts here (so `thread !== null` ⇒ thread
|
|
57
|
+
// room), but Discord models a thread as its own channel — the thread's id is
|
|
58
|
+
// in `chat` and `thread` stays null. The engagement gate and membership
|
|
59
|
+
// scoping need "is this a thread room?" independent of routing, so adapters
|
|
60
|
+
// set this explicitly. `parentChat` carries the parent channel id when the
|
|
61
|
+
// adapter knows it, so membership can be scoped to the room (channel), not
|
|
62
|
+
// the thread. Absent ⇒ not a thread room (or the adapter cannot tell).
|
|
63
|
+
room?: { kind: 'thread'; parentChat?: string }
|
|
54
64
|
text: string
|
|
55
65
|
// Prompt-only context for replied-to / quoted / linked messages. Kept out
|
|
56
66
|
// of `text` so the engagement gate sees only the human-authored body.
|
|
@@ -355,7 +365,8 @@ export type FetchHistoryResult =
|
|
|
355
365
|
// Registered per-adapter on the ChannelRouter alongside outbound/typing
|
|
356
366
|
// callbacks. Adapters that cannot fetch history (e.g. webhook-only future
|
|
357
367
|
// adapters) simply do not register one; the router answers
|
|
358
|
-
// 'history-not-supported' for those
|
|
368
|
+
// 'history-not-supported' for those, or 'history-adapter-unavailable' when the
|
|
369
|
+
// adapter is configured but failed to start (see setAdapterConfigured).
|
|
359
370
|
export type HistoryCallback = (args: FetchHistoryArgs) => Promise<FetchHistoryResult>
|
|
360
371
|
|
|
361
372
|
// Fetch a single message by its platform id from an arbitrary chat. Backs the
|
|
@@ -373,9 +384,11 @@ export type GetMessageArgs = {
|
|
|
373
384
|
export type GetMessageResult =
|
|
374
385
|
| { ok: true; message: ChannelHistoryMessage }
|
|
375
386
|
// `code: 'not-found'` is an expected miss (deleted/wrong id) the tool surfaces
|
|
376
|
-
// as a soft error; `code: 'not-supported'` means
|
|
377
|
-
//
|
|
378
|
-
|
|
387
|
+
// as a soft error; `code: 'not-supported'` means the adapter is not configured
|
|
388
|
+
// at all; `code: 'adapter-unavailable'` means it IS configured but currently
|
|
389
|
+
// has no live callback (e.g. failed to start), mirroring `fetchHistory`'s
|
|
390
|
+
// 'message-get-adapter-unavailable' string contract.
|
|
391
|
+
| { ok: false; error: string; code?: 'not-found' | 'not-supported' | 'adapter-unavailable' }
|
|
379
392
|
|
|
380
393
|
export type MessageGetCallback = (args: GetMessageArgs) => Promise<GetMessageResult>
|
|
381
394
|
|
|
@@ -398,7 +411,7 @@ export type ListChannelsArgs = {
|
|
|
398
411
|
|
|
399
412
|
export type ListChannelsResult =
|
|
400
413
|
| { ok: true; entries: ChannelListEntry[]; nextCursor?: string }
|
|
401
|
-
| { ok: false; error: string; code?: 'not-supported' }
|
|
414
|
+
| { ok: false; error: string; code?: 'not-supported' | 'adapter-unavailable' }
|
|
402
415
|
|
|
403
416
|
// Backs the `channel_read` tool's `mode: "list"`. Opt-in per adapter like
|
|
404
417
|
// history; the router answers 'list-not-supported' when none is registered.
|
package/src/cli/channel.ts
CHANGED
|
@@ -183,7 +183,11 @@ const setSub = defineCommand({
|
|
|
183
183
|
},
|
|
184
184
|
})
|
|
185
185
|
|
|
186
|
-
|
|
186
|
+
// Adapters that re-authenticate through a full interactive login replay rather
|
|
187
|
+
// than a token-field rotation (`channel set`). Discord (User) belongs here — its
|
|
188
|
+
// unofficial QR session expires and is refreshed by replaying the QR login, the
|
|
189
|
+
// same shape as LINE's QR flow. `discord-bot` stays in SETTABLE_ADAPTERS.
|
|
190
|
+
const REAUTHABLE_ADAPTERS = ['line', 'instagram', 'kakaotalk', 'webex', 'discord'] as const
|
|
187
191
|
type ReauthableAdapter = (typeof REAUTHABLE_ADAPTERS)[number]
|
|
188
192
|
|
|
189
193
|
const reauthSub = defineCommand({
|
|
@@ -405,9 +409,7 @@ async function resolveReauthableAdapter(
|
|
|
405
409
|
): Promise<ReauthableAdapter> {
|
|
406
410
|
if (requested !== undefined) {
|
|
407
411
|
if (!isReauthableAdapter(requested)) {
|
|
408
|
-
console.error(
|
|
409
|
-
errorLine(`Adapter "${requested}" does not support reauth. Supported: ${REAUTHABLE_ADAPTERS.join(', ')}.`),
|
|
410
|
-
)
|
|
412
|
+
console.error(errorLine(reauthAdapterRejectionMessage(requested)))
|
|
411
413
|
process.exit(1)
|
|
412
414
|
}
|
|
413
415
|
if (!configured.has(requested)) {
|
|
@@ -448,6 +450,14 @@ function isReauthableAdapter(value: string): value is ReauthableAdapter {
|
|
|
448
450
|
return (REAUTHABLE_ADAPTERS as ReadonlyArray<string>).includes(value)
|
|
449
451
|
}
|
|
450
452
|
|
|
453
|
+
// Returns the string (rather than exiting inline) so the routing stays testable.
|
|
454
|
+
export function reauthAdapterRejectionMessage(adapter: string): string {
|
|
455
|
+
if (isSettableAdapter(adapter)) {
|
|
456
|
+
return `Adapter "${adapter}" does not support reauth. Use \`typeclaw channel set ${adapter}\` to rotate its credentials.`
|
|
457
|
+
}
|
|
458
|
+
return `Adapter "${adapter}" does not support reauth. Supported: ${REAUTHABLE_ADAPTERS.join(', ')}.`
|
|
459
|
+
}
|
|
460
|
+
|
|
451
461
|
async function runReauth(cwd: string, adapter: ReauthableAdapter): Promise<void> {
|
|
452
462
|
switch (adapter) {
|
|
453
463
|
case 'line':
|
|
@@ -462,6 +472,9 @@ async function runReauth(cwd: string, adapter: ReauthableAdapter): Promise<void>
|
|
|
462
472
|
case 'webex':
|
|
463
473
|
await runWebexReauth(cwd)
|
|
464
474
|
return
|
|
475
|
+
case 'discord':
|
|
476
|
+
await runDiscordReauth(cwd)
|
|
477
|
+
return
|
|
465
478
|
}
|
|
466
479
|
}
|
|
467
480
|
|
|
@@ -540,6 +553,17 @@ async function runWebexReauth(cwd: string): Promise<void> {
|
|
|
540
553
|
await maybePromptReauthRefresh(cwd, 'webex')
|
|
541
554
|
}
|
|
542
555
|
|
|
556
|
+
async function runDiscordReauth(cwd: string): Promise<void> {
|
|
557
|
+
const result = await runDiscordBootstrap({ agentDir: cwd, onQrUrl: renderDiscordQrToTerminal })
|
|
558
|
+
if (!result.ok) {
|
|
559
|
+
console.error(errorLine(`Discord login failed: ${result.reason}`))
|
|
560
|
+
process.exit(1)
|
|
561
|
+
}
|
|
562
|
+
process.stdout.write(`${successLine('Discord credentials refreshed in secrets.json.')}\n`)
|
|
563
|
+
|
|
564
|
+
await maybePromptReauthRefresh(cwd, 'discord')
|
|
565
|
+
}
|
|
566
|
+
|
|
543
567
|
async function readExistingKakaotalkEmail(cwd: string): Promise<string | undefined> {
|
|
544
568
|
try {
|
|
545
569
|
const store = new SecretsKakaoCredentialStore({ mode: 'host', secretsPath: `${cwd}/secrets.json` })
|
|
@@ -771,17 +795,20 @@ function isSettableAdapter(value: string): value is SettableAdapter {
|
|
|
771
795
|
return (SETTABLE_ADAPTERS as ReadonlyArray<string>).includes(value)
|
|
772
796
|
}
|
|
773
797
|
|
|
798
|
+
// Returns the string (rather than exiting inline) so the routing stays testable.
|
|
799
|
+
export function setAdapterRejectionMessage(adapter: string): string {
|
|
800
|
+
if (isReauthableAdapter(adapter)) {
|
|
801
|
+
return `Adapter "${adapter}" does not support \`channel set\`. Use \`typeclaw channel reauth ${adapter}\` instead.`
|
|
802
|
+
}
|
|
803
|
+
if (isChannelKind(adapter)) {
|
|
804
|
+
return `Adapter "${adapter}" does not support \`channel set\`. Rotate its credentials by removing and re-adding it: \`typeclaw channel remove ${adapter} && typeclaw channel add ${adapter}\`.`
|
|
805
|
+
}
|
|
806
|
+
return `Unknown adapter "${adapter}". Expected one of: ${SETTABLE_ADAPTERS.join(', ')}.`
|
|
807
|
+
}
|
|
808
|
+
|
|
774
809
|
function validateSetAdapterArg(adapter: string, configured: Set<ChannelKind>): SettableAdapter {
|
|
775
810
|
if (!isSettableAdapter(adapter)) {
|
|
776
|
-
|
|
777
|
-
console.error(
|
|
778
|
-
errorLine(
|
|
779
|
-
`Adapter "${adapter}" does not support \`channel set\`. Use \`typeclaw channel reauth ${adapter}\` instead.`,
|
|
780
|
-
),
|
|
781
|
-
)
|
|
782
|
-
} else {
|
|
783
|
-
console.error(errorLine(`Unknown adapter "${adapter}". Expected one of: ${SETTABLE_ADAPTERS.join(', ')}.`))
|
|
784
|
-
}
|
|
811
|
+
console.error(errorLine(setAdapterRejectionMessage(adapter)))
|
|
785
812
|
process.exit(1)
|
|
786
813
|
}
|
|
787
814
|
if (!configured.has(adapter)) {
|
package/src/cli/command-meta.ts
CHANGED
|
@@ -27,6 +27,7 @@ export type BuiltinCommandName =
|
|
|
27
27
|
| 'tunnel'
|
|
28
28
|
| 'role'
|
|
29
29
|
| 'provider'
|
|
30
|
+
| 'mcp'
|
|
30
31
|
| 'model'
|
|
31
32
|
| 'mount'
|
|
32
33
|
| 'doctor'
|
|
@@ -60,6 +61,7 @@ export const BUILTIN_COMMANDS: readonly BuiltinCommandMeta[] = [
|
|
|
60
61
|
{ name: 'tunnel', description: 'manage public tunnels for channels and manual upstreams' },
|
|
61
62
|
{ name: 'role', description: 'manage role memberships on this agent' },
|
|
62
63
|
{ name: 'provider', description: 'manage LLM provider credentials in secrets.json' },
|
|
64
|
+
{ name: 'mcp', description: 'manage MCP server OAuth credentials' },
|
|
63
65
|
{ name: 'model', description: 'manage model profiles in typeclaw.json (models.default, ...)' },
|
|
64
66
|
{ name: 'mount', description: 'manage host files and directories mounted into the agent container' },
|
|
65
67
|
{ name: 'doctor', description: 'diagnose host, agent folder, and plugins; suggest fixes' },
|
package/src/cli/index.ts
CHANGED
|
@@ -33,6 +33,7 @@ const main = defineCommand({
|
|
|
33
33
|
tunnel: () => import('./tunnel').then((m) => m.tunnelCommand),
|
|
34
34
|
role: () => import('./role').then((m) => m.roleCommand),
|
|
35
35
|
provider: () => import('./provider').then((m) => m.providerCommand),
|
|
36
|
+
mcp: () => import('./mcp').then((m) => m.mcpCommand),
|
|
36
37
|
model: () => import('./model').then((m) => m.modelCommand),
|
|
37
38
|
mount: () => import('./mount').then((m) => m.mountCommand),
|
|
38
39
|
doctor: () => import('./doctor').then((m) => m.doctorCommand),
|
package/src/cli/mcp.ts
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
|
|
4
|
+
import { isCancel, log, note, text } from '@clack/prompts'
|
|
5
|
+
import { UnauthorizedError } from '@modelcontextprotocol/sdk/client/auth.js'
|
|
6
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
|
|
7
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
|
|
8
|
+
import { defineCommand } from 'citty'
|
|
9
|
+
|
|
10
|
+
import { loadConfigSync } from '@/config'
|
|
11
|
+
import { findAgentDir, isInitialized } from '@/init'
|
|
12
|
+
import { createFileMcpOAuthStore, TypeClawMcpOAuthProvider, listMcpCredentials } from '@/mcp'
|
|
13
|
+
import { SecretsBackend } from '@/secrets'
|
|
14
|
+
|
|
15
|
+
import { c, done, errorLine } from './ui'
|
|
16
|
+
|
|
17
|
+
const DEFAULT_CALLBACK_PORT = 1456
|
|
18
|
+
|
|
19
|
+
const authSub = defineCommand({
|
|
20
|
+
meta: {
|
|
21
|
+
name: 'auth',
|
|
22
|
+
description: 'authenticate an HTTP MCP server with OAuth',
|
|
23
|
+
},
|
|
24
|
+
args: {
|
|
25
|
+
server: { type: 'positional', description: 'MCP server name from typeclaw.json', required: true },
|
|
26
|
+
},
|
|
27
|
+
async run({ args }) {
|
|
28
|
+
const cwd = ensureAgentDir()
|
|
29
|
+
const result = await runMcpAuthFlow(cwd, args.server)
|
|
30
|
+
if (!result.ok) {
|
|
31
|
+
console.error(errorLine(result.reason))
|
|
32
|
+
process.exit(1)
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
const listSub = defineCommand({
|
|
38
|
+
meta: {
|
|
39
|
+
name: 'list',
|
|
40
|
+
description: 'show configured MCP servers and OAuth credential state',
|
|
41
|
+
},
|
|
42
|
+
run() {
|
|
43
|
+
const cwd = ensureAgentDir()
|
|
44
|
+
const config = loadConfigSync(cwd)
|
|
45
|
+
const credentials = listMcpCredentials(join(cwd, 'secrets.json'))
|
|
46
|
+
if (config.mcpServers.length === 0) {
|
|
47
|
+
console.log(c.dim('No MCP servers configured in typeclaw.json.'))
|
|
48
|
+
return
|
|
49
|
+
}
|
|
50
|
+
const nameWidth = Math.max(4, ...config.mcpServers.map((server) => server.name.length))
|
|
51
|
+
const typeWidth = 5
|
|
52
|
+
console.log(c.dim(`${'NAME'.padEnd(nameWidth)} ${'TYPE'.padEnd(typeWidth)} OAUTH`))
|
|
53
|
+
for (const server of config.mcpServers) {
|
|
54
|
+
const type = server.url === undefined ? 'stdio' : 'http'
|
|
55
|
+
const oauth = credentials[server.name] === undefined ? 'not configured' : 'configured'
|
|
56
|
+
console.log(`${server.name.padEnd(nameWidth)} ${type.padEnd(typeWidth)} ${oauth}`)
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
const logoutSub = defineCommand({
|
|
62
|
+
meta: {
|
|
63
|
+
name: 'logout',
|
|
64
|
+
description: 'remove OAuth credentials for an MCP server',
|
|
65
|
+
},
|
|
66
|
+
args: {
|
|
67
|
+
server: { type: 'positional', description: 'MCP server name from typeclaw.json', required: true },
|
|
68
|
+
},
|
|
69
|
+
run({ args }) {
|
|
70
|
+
const cwd = ensureAgentDir()
|
|
71
|
+
const removed = new SecretsBackend(join(cwd, 'secrets.json')).removeMcpCredentialSync(args.server)
|
|
72
|
+
if (!removed) log.info(`No OAuth credentials found for MCP server "${args.server}".`)
|
|
73
|
+
done({
|
|
74
|
+
title: c.green(`Removed OAuth credentials for MCP server "${args.server}".`),
|
|
75
|
+
hints: [{ label: 'Apply the secrets.json change:', command: 'typeclaw reload' }],
|
|
76
|
+
})
|
|
77
|
+
},
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
export const mcpCommand = defineCommand({
|
|
81
|
+
meta: {
|
|
82
|
+
name: 'mcp',
|
|
83
|
+
description: 'manage MCP server OAuth credentials',
|
|
84
|
+
},
|
|
85
|
+
subCommands: {
|
|
86
|
+
auth: authSub,
|
|
87
|
+
list: listSub,
|
|
88
|
+
logout: logoutSub,
|
|
89
|
+
},
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
export type McpAuthFlowResult = { ok: true } | { ok: false; reason: string }
|
|
93
|
+
|
|
94
|
+
export async function runMcpAuthFlow(cwd: string, serverName: string): Promise<McpAuthFlowResult> {
|
|
95
|
+
const config = loadConfigSync(cwd)
|
|
96
|
+
const server = config.mcpServers.find((candidate) => candidate.name === serverName)
|
|
97
|
+
if (server === undefined) return { ok: false, reason: `MCP server "${serverName}" is not configured.` }
|
|
98
|
+
if (server.url === undefined)
|
|
99
|
+
return { ok: false, reason: `MCP server "${serverName}" is stdio-only; OAuth is HTTP-only.` }
|
|
100
|
+
|
|
101
|
+
const redirectUrl = `http://localhost:${DEFAULT_CALLBACK_PORT}/callback`
|
|
102
|
+
let authorizationUrl: URL | undefined
|
|
103
|
+
const provider = new TypeClawMcpOAuthProvider(serverName, createFileMcpOAuthStore(join(cwd, 'secrets.json')), {
|
|
104
|
+
mode: 'host',
|
|
105
|
+
redirectUrl,
|
|
106
|
+
clientName: 'typeclaw',
|
|
107
|
+
onRedirect: (url) => {
|
|
108
|
+
authorizationUrl = url
|
|
109
|
+
},
|
|
110
|
+
})
|
|
111
|
+
const callback = createCallbackServer(DEFAULT_CALLBACK_PORT)
|
|
112
|
+
try {
|
|
113
|
+
const transport = new StreamableHTTPClientTransport(new URL(server.url), { authProvider: provider })
|
|
114
|
+
const client = new Client({ name: 'typeclaw', version: '0.17.0' }, { capabilities: {} })
|
|
115
|
+
try {
|
|
116
|
+
await client.connect(transport)
|
|
117
|
+
await client.close()
|
|
118
|
+
done({ title: c.green(`MCP server "${serverName}" is already authenticated.`), hints: [] })
|
|
119
|
+
return { ok: true }
|
|
120
|
+
} catch (cause) {
|
|
121
|
+
await client.close().catch(() => undefined)
|
|
122
|
+
if (!(cause instanceof UnauthorizedError)) throw cause
|
|
123
|
+
}
|
|
124
|
+
if (authorizationUrl === undefined)
|
|
125
|
+
return { ok: false, reason: 'OAuth server did not provide an authorization URL.' }
|
|
126
|
+
renderAuthorizationUrl(serverName, authorizationUrl)
|
|
127
|
+
openBrowserBestEffort(authorizationUrl)
|
|
128
|
+
const expectedState = await provider.state()
|
|
129
|
+
const codeResult = await Promise.race([callback.code, promptForCodeOrUrl()])
|
|
130
|
+
if (expectedState !== undefined && codeResult.state !== undefined && codeResult.state !== expectedState) {
|
|
131
|
+
return { ok: false, reason: 'OAuth callback state did not match the authorization request.' }
|
|
132
|
+
}
|
|
133
|
+
await transport.finishAuth(codeResult.code)
|
|
134
|
+
await verifyMcpAuth(server.url, provider)
|
|
135
|
+
done({
|
|
136
|
+
title: c.green(`Authenticated MCP server "${serverName}".`),
|
|
137
|
+
hints: [{ label: 'Apply the secrets.json change:', command: 'typeclaw reload' }],
|
|
138
|
+
})
|
|
139
|
+
return { ok: true }
|
|
140
|
+
} catch (cause) {
|
|
141
|
+
return { ok: false, reason: cause instanceof Error ? cause.message : String(cause) }
|
|
142
|
+
} finally {
|
|
143
|
+
callback.stop()
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function ensureAgentDir(): string {
|
|
148
|
+
const cwd = findAgentDir(process.cwd()) ?? process.cwd()
|
|
149
|
+
if (!isInitialized(cwd)) {
|
|
150
|
+
console.error(errorLine('TypeClaw config file not found. Run `typeclaw init` first, or cd into an agent folder.'))
|
|
151
|
+
process.exit(1)
|
|
152
|
+
}
|
|
153
|
+
return cwd
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function createCallbackServer(port: number): { code: Promise<{ code: string; state?: string }>; stop(): void } {
|
|
157
|
+
let resolveCode!: (value: { code: string; state?: string }) => void
|
|
158
|
+
const code = new Promise<{ code: string; state?: string }>((resolve) => {
|
|
159
|
+
resolveCode = resolve
|
|
160
|
+
})
|
|
161
|
+
const server = Bun.serve({
|
|
162
|
+
hostname: '127.0.0.1',
|
|
163
|
+
port,
|
|
164
|
+
fetch(req) {
|
|
165
|
+
const url = new URL(req.url)
|
|
166
|
+
if (url.pathname !== '/callback') return new Response('Not found', { status: 404 })
|
|
167
|
+
const parsed = parseCodeInput(url)
|
|
168
|
+
if (parsed === null) return new Response('Missing OAuth code', { status: 400 })
|
|
169
|
+
resolveCode(parsed)
|
|
170
|
+
return new Response('TypeClaw MCP OAuth complete. You can close this tab.')
|
|
171
|
+
},
|
|
172
|
+
})
|
|
173
|
+
return { code, stop: () => server.stop(true) }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function renderAuthorizationUrl(serverName: string, url: URL): void {
|
|
177
|
+
note(
|
|
178
|
+
[
|
|
179
|
+
`Open this URL in your browser to authenticate MCP server "${serverName}".`,
|
|
180
|
+
'',
|
|
181
|
+
'If the browser cannot reach localhost after sign-in, copy the full redirect URL or code and paste it below.',
|
|
182
|
+
].join('\n'),
|
|
183
|
+
'MCP OAuth',
|
|
184
|
+
)
|
|
185
|
+
console.log(url.toString())
|
|
186
|
+
console.log('')
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function openBrowserBestEffort(url: URL): void {
|
|
190
|
+
const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open'
|
|
191
|
+
const args = process.platform === 'win32' ? ['/c', 'start', '', url.toString()] : [url.toString()]
|
|
192
|
+
const child = spawn(command, args, { stdio: 'ignore', detached: true })
|
|
193
|
+
child.on('error', () => undefined)
|
|
194
|
+
child.unref()
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async function promptForCodeOrUrl(): Promise<{ code: string; state?: string }> {
|
|
198
|
+
const value = await text({
|
|
199
|
+
message: 'After signing in, paste the code or full redirect URL:',
|
|
200
|
+
placeholder: 'code, or http://localhost:1456/callback?code=...&state=...',
|
|
201
|
+
})
|
|
202
|
+
if (isCancel(value)) throw new Error('OAuth login cancelled by user')
|
|
203
|
+
const parsed = parseCodeInput(value)
|
|
204
|
+
if (parsed === null) throw new Error('OAuth callback did not include a code')
|
|
205
|
+
return parsed
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function parseCodeInput(input: string | URL): { code: string; state?: string } | null {
|
|
209
|
+
if (input instanceof URL) {
|
|
210
|
+
const code = input.searchParams.get('code')
|
|
211
|
+
if (code === null || code.trim() === '') return null
|
|
212
|
+
const state = input.searchParams.get('state') ?? undefined
|
|
213
|
+
return { code, ...(state === undefined ? {} : { state }) }
|
|
214
|
+
}
|
|
215
|
+
const trimmed = input.trim()
|
|
216
|
+
if (trimmed === '') return null
|
|
217
|
+
try {
|
|
218
|
+
return parseCodeInput(new URL(trimmed))
|
|
219
|
+
} catch {
|
|
220
|
+
return { code: trimmed }
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function verifyMcpAuth(url: string, authProvider: TypeClawMcpOAuthProvider): Promise<void> {
|
|
225
|
+
const client = new Client({ name: 'typeclaw', version: '0.17.0' }, { capabilities: {} })
|
|
226
|
+
try {
|
|
227
|
+
const transport = new StreamableHTTPClientTransport(new URL(url), { authProvider })
|
|
228
|
+
await client.connect(transport)
|
|
229
|
+
await client.listTools()
|
|
230
|
+
} finally {
|
|
231
|
+
await client.close().catch(() => undefined)
|
|
232
|
+
}
|
|
233
|
+
}
|
package/src/hostd/daemon.ts
CHANGED
|
@@ -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
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
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
|
package/src/hostd/protocol.ts
CHANGED
|
@@ -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/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(
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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>(
|
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,
|
package/src/mcp/manager.ts
CHANGED
|
@@ -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) {
|