Skip to content

Instantly share code, notes, and snippets.

@leehanchung
Last active March 8, 2025 09:08
Show Gist options
  • Save leehanchung/b5b2803a5c1fcb503afedd2105f7d0f3 to your computer and use it in GitHub Desktop.
Save leehanchung/b5b2803a5c1fcb503afedd2105f7d0f3 to your computer and use it in GitHub Desktop.
claude code mcp implementation
async function OX9(I, G) {
let Z =
G.type === 'sse'
? new jN1(new URL(G.url))
: new MN1({
command: G.command,
args: G.args,
env: { ...process.env, ...G.env },
stderr: 'pipe',
}),
d = new vN1({ name: 'claude', version: '0.1.0' }, { capabilities: {} }),
W = 5000,
w = d.connect(Z),
B = new Promise((C, V) => {
let A = setTimeout(() => {
V(new Error(`Connection to MCP server "${I}" timed out after 5000ms`))
}, 5000)
w.then(
() => clearTimeout(A),
() => clearTimeout(A),
)
})
if ((await Promise.race([w, B]), G.type === 'stdio'))
Z.stderr?.on('data', (C) => {
let V = C.toString().trim()
if (V) Pz(I, `Server stderr: ${V}`)
})
return d
}
function kU2(I) {
let G = f4()
if (G.approvedMcprcServers?.includes(I)) return 'approved'
if (G.rejectedMcprcServers?.includes(I)) return 'rejected'
return 'pending'
}
var hN1 = s2(async () => {
let I = F2().mcpServers ?? {},
G = KM(),
Z = f4().mcpServers ?? {},
d = k21(G, (w, B) => kU2(B) === 'approved'),
W = { ...I, ...d, ...Z }
return await Promise.all(
Object.entries(W).map(async ([w, B]) => {
try {
let C = await OX9(w, B)
return (
s1('tengu_mcp_server_connection_succeeded', {}), { name: w, client: C, type: 'connected' }
)
} catch (C) {
return (
s1('tengu_mcp_server_connection_failed', {}),
Pz(w, `Connection failed: ${C instanceof Error ? C.message : String(C)}`),
{ name: w, type: 'failed' }
)
}
}),
)
})
async function hU2(I, G, Z) {
let d = await hN1()
return (
await Promise.allSettled(
d.map(async (w) => {
if (w.type === 'failed') return null
try {
if (!(await w.client.getServerCapabilities())?.[Z]) return null
return { client: w, result: await w.client.request(I, G) }
} catch (B) {
if (w.type === 'connected')
Pz(
w.name,
`Failed to request '${I.method}': ${B instanceof Error ? B.message : String(B)}`,
)
return null
}
}),
)
)
.filter((w) => w.status === 'fulfilled')
.map((w) => w.value)
.filter((w) => w !== null)
}
var xU2 = s2(async () => {
return (await hU2({ method: 'tools/list' }, oO, 'tools')).flatMap(
({ client: G, result: { tools: Z } }) =>
Z.map((d) => ({
...$U2,
name: 'mcp__' + G.name + '__' + d.name,
async description() {
return d.description ?? ''
},
async prompt() {
return d.description ?? ''
},
inputJSONSchema: d.inputSchema,
async *call(W) {
let w = await uX9({ client: G, tool: d.name, args: W })
yield { type: 'result', data: w, resultForAssistant: w }
},
userFacingName() {
return `${G.name}:${d.name} (MCP)`
},
})),
)
})
async function uX9({ client: { client: I, name: G }, tool: Z, args: d }) {
let W = await I.callTool({ name: Z, arguments: d }, yR)
if ('isError' in W && W.isError) {
let w = `Error calling tool ${Z}: ${W.error}`
throw (Pz(G, w), Error(w))
}
if ('toolResult' in W) return String(W.toolResult)
if ('content' in W && Array.isArray(W.content))
return W.content.map((w) => {
if (w.type === 'image')
return {
type: 'image',
source: { type: 'base64', data: String(w.data), media_type: w.mimeType },
}
return w
})
throw Error(`Unexpected response format from tool ${Z}`)
}
var cU2 = s2(async () => {
return (await hU2({ method: 'prompts/list' }, sO, 'prompts')).flatMap(
({ client: G, result: Z }) =>
Z.prompts?.map((d) => {
let W = Object.values(d.arguments ?? {}).map((w) => w.name)
return {
type: 'prompt',
name: 'mcp__' + G.name + '__' + d.name,
description: d.description ?? '',
isEnabled: !0,
isHidden: !1,
progressMessage: 'running',
userFacingName() {
return `${G.name}:${d.name} (MCP)`
},
argNames: W,
async getPromptForCommand(w) {
let B = w.split(' ')
return await TX9({ name: d.name, client: G }, x21(W, B))
},
}
}),
)
})
async function TX9({ name: I, client: G }, Z) {
try {
return (await G.client.getPrompt({ name: I, arguments: Z })).messages.map((W) => ({
role: W.role,
content: [
W.content.type === 'text'
? { type: 'text', text: W.content.text }
: {
type: 'image',
source: {
data: String(W.content.data),
media_type: W.content.mimeType,
type: 'base64',
},
},
],
}))
} catch (d) {
throw (
(Pz(G.name, `Error running command '${I}': ${d instanceof Error ? d.message : String(d)}`), d)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment