forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcpServer.ts
More file actions
293 lines (277 loc) · 10.8 KB
/
Copy pathmcpServer.ts
File metadata and controls
293 lines (277 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import {
type ClaudeForChromeContext,
createClaudeForChromeMcpServer,
type Logger,
type PermissionMode,
} from '@ant/claude-for-chrome-mcp'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
import { format } from 'util'
import { shutdownDatadog } from '../../services/analytics/datadog.js'
import { shutdown1PEventLogging } from '../../services/analytics/firstPartyEventLogger.js'
import { getFeatureValue_CACHED_MAY_BE_STALE } from '../../services/analytics/growthbook.js'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from '../../services/analytics/index.js'
import { initializeAnalyticsSink } from '../../services/analytics/sink.js'
import { getClaudeAIOAuthTokens } from '../auth.js'
import { enableConfigs, getGlobalConfig, saveGlobalConfig } from '../config.js'
import { logForDebugging } from '../debug.js'
import { isEnvTruthy } from '../envUtils.js'
import { sideQuery } from '../sideQuery.js'
import { getAllSocketPaths, getSecureSocketPath } from './common.js'
const EXTENSION_DOWNLOAD_URL = 'https://claude.ai/chrome'
const BUG_REPORT_URL =
'https://github.com/anthropics/claude-code/issues/new?labels=bug,claude-in-chrome'
// String metadata keys safe to forward to analytics. Keys like error_message
// are excluded because they could contain page content or user data.
const SAFE_BRIDGE_STRING_KEYS = new Set([
'bridge_status',
'error_type',
'tool_name',
])
const PERMISSION_MODES: readonly PermissionMode[] = [
'ask',
'skip_all_permission_checks',
'follow_a_plan',
]
function isPermissionMode(raw: string): raw is PermissionMode {
return PERMISSION_MODES.some(m => m === raw)
}
/**
* Resolves the Chrome bridge URL based on environment and feature flag.
* Bridge is used when the feature flag is enabled; ant users always get
* bridge. API key / 3P users fall back to native messaging.
*/
function getChromeBridgeUrl(): string | undefined {
const bridgeEnabled =
process.env.USER_TYPE === 'ant' ||
getFeatureValue_CACHED_MAY_BE_STALE('tengu_copper_bridge', false)
if (!bridgeEnabled) {
return undefined
}
if (
isEnvTruthy(process.env.USE_LOCAL_OAUTH) ||
isEnvTruthy(process.env.LOCAL_BRIDGE)
) {
return 'ws://localhost:8765'
}
if (isEnvTruthy(process.env.USE_STAGING_OAUTH)) {
return 'wss://bridge-staging.claudeusercontent.com'
}
return 'wss://bridge.claudeusercontent.com'
}
function isLocalBridge(): boolean {
return (
isEnvTruthy(process.env.USE_LOCAL_OAUTH) ||
isEnvTruthy(process.env.LOCAL_BRIDGE)
)
}
/**
* Build the ClaudeForChromeContext used by both the subprocess MCP server
* and the in-process path in the MCP client.
*/
export function createChromeContext(
env?: Record<string, string>,
): ClaudeForChromeContext {
const logger = new DebugLogger()
const chromeBridgeUrl = getChromeBridgeUrl()
logger.info(`Bridge URL: ${chromeBridgeUrl ?? 'none (using native socket)'}`)
const rawPermissionMode =
env?.CLAUDE_CHROME_PERMISSION_MODE ??
process.env.CLAUDE_CHROME_PERMISSION_MODE
let initialPermissionMode: PermissionMode | undefined
if (rawPermissionMode) {
if (isPermissionMode(rawPermissionMode)) {
initialPermissionMode = rawPermissionMode
} else {
logger.warn(
`Invalid CLAUDE_CHROME_PERMISSION_MODE "${rawPermissionMode}". Valid values: ${PERMISSION_MODES.join(', ')}`,
)
}
}
return {
serverName: 'Claude in Chrome',
logger,
socketPath: getSecureSocketPath(),
getSocketPaths: getAllSocketPaths,
clientTypeId: 'claude-code',
onAuthenticationError: () => {
logger.warn(
'Authentication error occurred. Please ensure you are logged into the Claude browser extension with the same claude.ai account as Claude Code.',
)
},
onToolCallDisconnected: () => {
return `Browser extension is not connected. Please ensure the Claude browser extension is installed and running (${EXTENSION_DOWNLOAD_URL}), and that you are logged into claude.ai with the same account as Claude Code. If this is your first time connecting to Chrome, you may need to restart Chrome for the installation to take effect. If you continue to experience issues, please report a bug: ${BUG_REPORT_URL}`
},
onExtensionPaired: (deviceId: string, name: string) => {
saveGlobalConfig(config => {
if (
config.chromeExtension?.pairedDeviceId === deviceId &&
config.chromeExtension?.pairedDeviceName === name
) {
return config
}
return {
...config,
chromeExtension: {
pairedDeviceId: deviceId,
pairedDeviceName: name,
},
}
})
logger.info(`Paired with "${name}" (${deviceId.slice(0, 8)})`)
},
getPersistedDeviceId: () => {
return getGlobalConfig().chromeExtension?.pairedDeviceId
},
...(chromeBridgeUrl && {
bridgeConfig: {
url: chromeBridgeUrl,
getUserId: async () => {
return getGlobalConfig().oauthAccount?.accountUuid
},
getOAuthToken: async () => {
return getClaudeAIOAuthTokens()?.accessToken ?? ''
},
...(isLocalBridge() && { devUserId: 'dev_user_local' }),
},
}),
...(initialPermissionMode && { initialPermissionMode }),
// Wire inference for the browser_task tool — the chrome-mcp server runs
// a lightning-mode agent loop in Node and calls the extension's
// lightning_turn tool once per iteration for execution.
//
// Ant-only: the extension's lightning_turn is build-time-gated via
// import.meta.env.ANT_ONLY_BUILD — the whole lightning/ module graph is
// tree-shaken from the public extension build (build:prod greps for a
// marker to verify). Without this injection, the Node MCP server's
// ListTools also filters browser_task + lightning_turn out, so external
// users never see the tools advertised. Three independent gates.
//
// Types inlined: AnthropicMessagesRequest/Response live in
// @ant/claude-for-chrome-mcp@0.4.0 which isn't published yet. CI installs
// 0.3.0. The callAnthropicMessages field is also 0.4.0-only, but spreading
// an extra property into ClaudeForChromeContext is fine against either
// version — 0.3.0 sees an unknown field (allowed in spread), 0.4.0 sees a
// structurally-matching one. Once 0.4.0 is published, this can switch to
// the package's exported types and the dep can be bumped.
...(process.env.USER_TYPE === 'ant' && {
callAnthropicMessages: async (req: {
model: string
max_tokens: number
system: string
messages: Parameters<typeof sideQuery>[0]['messages']
stop_sequences?: string[]
signal?: AbortSignal
}): Promise<{
content: Array<{ type: 'text'; text: string }>
stop_reason: string | null
usage?: { input_tokens: number; output_tokens: number }
}> => {
// sideQuery handles OAuth attribution fingerprint, proxy, model betas.
// skipSystemPromptPrefix: the lightning prompt is complete on its own;
// the CLI prefix would dilute the batching instructions.
// tools: [] is load-bearing — without it Sonnet emits
// <function_calls> XML before the text commands. Original
// lightning-harness.js (apps repo) does the same.
const response = await sideQuery({
model: req.model,
system: req.system,
messages: req.messages,
max_tokens: req.max_tokens,
stop_sequences: req.stop_sequences,
signal: req.signal,
skipSystemPromptPrefix: true,
tools: [],
querySource: 'chrome_mcp',
})
// BetaContentBlock is TextBlock | ThinkingBlock | ToolUseBlock | ...
// Only text blocks carry the model's command output.
const textBlocks: Array<{ type: 'text'; text: string }> = []
for (const b of response.content) {
if (b.type === 'text') {
textBlocks.push({ type: 'text', text: b.text })
}
}
return {
content: textBlocks,
stop_reason: response.stop_reason,
usage: {
input_tokens: response.usage.input_tokens,
output_tokens: response.usage.output_tokens,
},
}
},
}),
trackEvent: (eventName, metadata) => {
const safeMetadata: {
[key: string]:
| boolean
| number
| AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS
| undefined
} = {}
if (metadata) {
for (const [key, value] of Object.entries(metadata)) {
// Rename 'status' to 'bridge_status' to avoid Datadog's reserved field
const safeKey = key === 'status' ? 'bridge_status' : key
if (typeof value === 'boolean' || typeof value === 'number') {
safeMetadata[safeKey] = value
} else if (
typeof value === 'string' &&
SAFE_BRIDGE_STRING_KEYS.has(safeKey)
) {
// Only forward allowlisted string keys — fields like error_message
// could contain page content or user data
safeMetadata[safeKey] =
value as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS
}
}
}
logEvent(eventName, safeMetadata)
},
}
}
export async function runClaudeInChromeMcpServer(): Promise<void> {
enableConfigs()
initializeAnalyticsSink()
const context = createChromeContext()
const server = createClaudeForChromeMcpServer(context)
const transport = new StdioServerTransport()
// Exit when parent process dies (stdin pipe closes).
// Flush analytics before exiting so final-batch events (e.g. disconnect) aren't lost.
let exiting = false
const shutdownAndExit = async (): Promise<void> => {
if (exiting) {
return
}
exiting = true
await shutdown1PEventLogging()
await shutdownDatadog()
// eslint-disable-next-line custom-rules/no-process-exit
process.exit(0)
}
process.stdin.on('end', () => void shutdownAndExit())
process.stdin.on('error', () => void shutdownAndExit())
logForDebugging('[Claude in Chrome] Starting MCP server')
await server.connect(transport)
logForDebugging('[Claude in Chrome] MCP server started')
}
class DebugLogger implements Logger {
silly(message: string, ...args: unknown[]): void {
logForDebugging(format(message, ...args), { level: 'debug' })
}
debug(message: string, ...args: unknown[]): void {
logForDebugging(format(message, ...args), { level: 'debug' })
}
info(message: string, ...args: unknown[]): void {
logForDebugging(format(message, ...args), { level: 'info' })
}
warn(message: string, ...args: unknown[]): void {
logForDebugging(format(message, ...args), { level: 'warn' })
}
error(message: string, ...args: unknown[]): void {
logForDebugging(format(message, ...args), { level: 'error' })
}
}