@sanity/context-langchain 0.0.0-stage → 0.1.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.
- package/README.md +43 -2
- package/dist/index.d.ts +35 -0
- package/dist/index.js +122 -0
- package/dist/index.js.map +1 -0
- package/package.json +67 -3
- package/src/createSanityContext.ts +119 -0
- package/src/describeError.ts +59 -0
- package/src/index.ts +3 -0
- package/src/options.ts +16 -0
package/README.md
CHANGED
|
@@ -1,3 +1,44 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sanity/context-langchain
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Sanity Context for [LangChain](https://js.langchain.com) agents. Connect a LangChain agent to a Context MCP endpoint. The agent gets the endpoint's current tools on every run, so changes to the endpoint's sources in the Context app reach it without a restart. The agent loads the initial context itself, through the `initial_context` tool.
|
|
4
|
+
|
|
5
|
+
It takes the endpoint URL and an organization API token with Context access (Viewer is enough). Keep the token server-side. Create one connector per endpoint and token, and reuse it across runs.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @sanity/context-langchain langchain @langchain/core @langchain/langgraph @langchain/mcp-adapters @langchain/anthropic
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Install the package for your model provider; the example uses `@langchain/anthropic`.
|
|
14
|
+
|
|
15
|
+
## Use it
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import {createSanityContext} from '@sanity/context-langchain'
|
|
19
|
+
import {createAgent} from 'langchain'
|
|
20
|
+
|
|
21
|
+
const sanity = createSanityContext({
|
|
22
|
+
url: process.env.SANITY_CONTEXT_MCP_URL!,
|
|
23
|
+
token: process.env.SANITY_ORGANIZATION_TOKEN!,
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
const agent = createAgent({
|
|
27
|
+
model: 'anthropic:claude-sonnet-5-5',
|
|
28
|
+
systemPrompt: 'You are a support agent.',
|
|
29
|
+
// First, so other middleware sees the Sanity tools.
|
|
30
|
+
middleware: [sanity.middleware],
|
|
31
|
+
})
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
- Requires `langchain` 1.6 or later.
|
|
35
|
+
- Before every model call, the middleware lists the endpoint's tools, one request per step.
|
|
36
|
+
- A Sanity tool call that fails reaches the model as an error it can act on. Like any middleware that wraps tool calls, it makes LangChain rethrow errors from your own tools; add LangChain's `toolErrorMiddleware` to send those to the model.
|
|
37
|
+
|
|
38
|
+
## Errors
|
|
39
|
+
|
|
40
|
+
- A missing URL or token, or a URL that isn't https, throws when you create the connector.
|
|
41
|
+
- When the tools can't be listed, the agent run fails with `Could not connect to Sanity Context: …`, or `Sanity Context rejected the token …` for a 401 or 403.
|
|
42
|
+
- Tool results contain your content, so anyone who can edit that content can influence what the agent does.
|
|
43
|
+
|
|
44
|
+
See the [Sanity Context guide for LangChain](https://www.sanity.io/docs/context/connect-langchain) for setting up an endpoint and a token.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import {AgentMiddleware} from 'langchain'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Connects a LangChain agent to a Context MCP endpoint. Nothing is fetched until the agent runs.
|
|
5
|
+
* Create one per endpoint and token, and reuse it across runs.
|
|
6
|
+
*
|
|
7
|
+
* @public
|
|
8
|
+
*/
|
|
9
|
+
export declare function createSanityContext(options: SanityContextOptions): SanityContextLangChain
|
|
10
|
+
|
|
11
|
+
/** @public */
|
|
12
|
+
export declare interface SanityContextLangChain {
|
|
13
|
+
/**
|
|
14
|
+
* Pass to `createAgent({middleware: [...]})` as the first entry, so other middleware sees the
|
|
15
|
+
* Sanity tools. Before every model call it lists the endpoint's current tools, one request to the
|
|
16
|
+
* endpoint per step, and the call fails if they can't be listed.
|
|
17
|
+
*
|
|
18
|
+
* Errors from the Sanity tools go to the model. Like any middleware that wraps tool calls, it
|
|
19
|
+
* makes LangChain rethrow errors from the agent's own tools; add LangChain's
|
|
20
|
+
* `toolErrorMiddleware` to send those to the model instead.
|
|
21
|
+
*/
|
|
22
|
+
middleware: AgentMiddleware
|
|
23
|
+
/** Closes the connection to the endpoint. Optional: the process exits without it. */
|
|
24
|
+
close: () => Promise<void>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** @public */
|
|
28
|
+
export declare interface SanityContextOptions {
|
|
29
|
+
/** The Context MCP endpoint URL. */
|
|
30
|
+
url: string
|
|
31
|
+
/** An organization API token with Context access. */
|
|
32
|
+
token: string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export {}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { MCPAdapter, ToolException } from "@langchain/mcp-adapters";
|
|
2
|
+
import { createMiddleware, ToolMessage } from "langchain";
|
|
3
|
+
function describeError(error) {
|
|
4
|
+
try {
|
|
5
|
+
return httpError(error)?.text ?? messageOf(error).split(`
|
|
6
|
+
`)[0] ?? "";
|
|
7
|
+
} catch {
|
|
8
|
+
return "Unknown error";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
function connectionError(error) {
|
|
12
|
+
const http = httpError(error), detail = http?.text ?? describeError(error), message = http?.status === 401 || http?.status === 403 ? `Sanity Context rejected the token (${detail}). Use an organization API token with Context access.` : `Could not connect to Sanity Context: ${detail}`;
|
|
13
|
+
return new Error(message, { cause: error });
|
|
14
|
+
}
|
|
15
|
+
function httpError(error) {
|
|
16
|
+
try {
|
|
17
|
+
return findHttpError(error);
|
|
18
|
+
} catch {
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function findHttpError(error) {
|
|
23
|
+
let e = error;
|
|
24
|
+
for (let depth = 0; depth < 10 && e && typeof e == "object"; depth++) {
|
|
25
|
+
const { status, data, cause } = e;
|
|
26
|
+
if (typeof status == "number") {
|
|
27
|
+
const detail = serverMessage(typeof data?.text == "string" ? data.text : messageOf(e));
|
|
28
|
+
return { status, text: detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}` };
|
|
29
|
+
}
|
|
30
|
+
e = cause;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function messageOf(error) {
|
|
34
|
+
const message = error?.message;
|
|
35
|
+
return typeof message == "string" ? message : String(error);
|
|
36
|
+
}
|
|
37
|
+
function serverMessage(text) {
|
|
38
|
+
try {
|
|
39
|
+
const body = JSON.parse(text.slice(text.indexOf("{"), text.lastIndexOf("}") + 1)), message = body?.error?.message ?? body?.message ?? body?.error;
|
|
40
|
+
return typeof message == "string" ? message : void 0;
|
|
41
|
+
} catch {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function validateOptions({ url, token }) {
|
|
46
|
+
if (!url) throw new Error("Sanity Context needs a url: the Context MCP endpoint URL.");
|
|
47
|
+
if (!token)
|
|
48
|
+
throw new Error("Sanity Context needs a token: an organization API token with Context access.");
|
|
49
|
+
if (!URL.canParse(url) || new URL(url).protocol !== "https:")
|
|
50
|
+
throw new Error("Sanity Context needs an https URL.");
|
|
51
|
+
}
|
|
52
|
+
function createSanityContext(options) {
|
|
53
|
+
validateOptions(options);
|
|
54
|
+
const { url, token } = options, client = new MCPAdapter({
|
|
55
|
+
prefixToolNameWithServerName: !1,
|
|
56
|
+
servers: {
|
|
57
|
+
sanity: {
|
|
58
|
+
transport: "http",
|
|
59
|
+
url,
|
|
60
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
61
|
+
// The endpoint speaks the initialize handshake over streamable HTTP. Probing for newer
|
|
62
|
+
// protocols and falling back to SSE costs requests and hides a 404 behind the SSE error.
|
|
63
|
+
mode: "legacy",
|
|
64
|
+
automaticSSEFallback: !1
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}), listTools = async () => {
|
|
68
|
+
let timer;
|
|
69
|
+
try {
|
|
70
|
+
const tools = await Promise.race([
|
|
71
|
+
client.listTools(),
|
|
72
|
+
new Promise((_, reject) => {
|
|
73
|
+
timer = setTimeout(() => reject(new Error("Timed out after 10 seconds")), 1e4);
|
|
74
|
+
})
|
|
75
|
+
]);
|
|
76
|
+
for (const tool of tools) tool.verboseParsingErrors = !0;
|
|
77
|
+
return tools;
|
|
78
|
+
} catch (error) {
|
|
79
|
+
throw connectionError(error);
|
|
80
|
+
} finally {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
}
|
|
83
|
+
}, warnedCollisions = /* @__PURE__ */ new Set();
|
|
84
|
+
let shown;
|
|
85
|
+
return { middleware: createMiddleware({
|
|
86
|
+
name: "SanityContext",
|
|
87
|
+
wrapModelCall: async (request, handler) => {
|
|
88
|
+
const taken = new Set(request.tools.map((t) => t.name)), tools = (await listTools()).filter((tool) => taken.has(tool.name) ? (warnedCollisions.has(tool.name) || (warnedCollisions.add(tool.name), console.warn(
|
|
89
|
+
`[sanity-context] Skipping the Sanity Context tool "${tool.name}": the agent already has a tool with that name.`
|
|
90
|
+
)), !1) : !0);
|
|
91
|
+
return shown = new Map(tools.map((tool) => [tool.name, tool])), handler({ ...request, tools: [...request.tools, ...tools] });
|
|
92
|
+
},
|
|
93
|
+
wrapToolCall: async (request, handler) => {
|
|
94
|
+
if (request.tool) return handler(request);
|
|
95
|
+
const name = request.toolCall.name, toolError = (content) => new ToolMessage({
|
|
96
|
+
content,
|
|
97
|
+
tool_call_id: request.toolCall.id ?? "",
|
|
98
|
+
name,
|
|
99
|
+
status: "error"
|
|
100
|
+
});
|
|
101
|
+
if (!shown)
|
|
102
|
+
try {
|
|
103
|
+
shown = new Map((await listTools()).map((tool2) => [tool2.name, tool2]));
|
|
104
|
+
} catch (error) {
|
|
105
|
+
return toolError(error.message);
|
|
106
|
+
}
|
|
107
|
+
const tool = shown.get(name);
|
|
108
|
+
if (!tool) return handler(request);
|
|
109
|
+
try {
|
|
110
|
+
return await handler({ ...request, tool });
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (!(error instanceof ToolException)) throw error;
|
|
113
|
+
const http = httpError(error)?.text;
|
|
114
|
+
return toolError(http ? `Error calling tool ${name}: ${http}` : describeError(error));
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}), close: () => client.close() };
|
|
118
|
+
}
|
|
119
|
+
export {
|
|
120
|
+
createSanityContext
|
|
121
|
+
};
|
|
122
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/describeError.ts","../src/options.ts","../src/createSanityContext.ts"],"sourcesContent":["/**\n * One line describing a failed MCP request. An HTTP error becomes its status and the server's own\n * message, without the raw response body, which can be a gateway's HTML page.\n */\nexport function describeError(error: unknown): string {\n try {\n return httpError(error)?.text ?? messageOf(error).split('\\n')[0] ?? ''\n } catch {\n return 'Unknown error'\n }\n}\n\n/** The error to throw when the endpoint's tools can't be listed. */\nexport function connectionError(error: unknown): Error {\n const http = httpError(error)\n const detail = http?.text ?? describeError(error)\n const message =\n http?.status === 401 || http?.status === 403\n ? `Sanity Context rejected the token (${detail}). Use an organization API token with Context access.`\n : `Could not connect to Sanity Context: ${detail}`\n return new Error(message, {cause: error})\n}\n\n/** The status and server message of the first HTTP error in the cause chain, if there is one. */\nexport function httpError(error: unknown): {status: number; text: string} | undefined {\n try {\n return findHttpError(error)\n } catch {\n return undefined\n }\n}\n\nfunction findHttpError(error: unknown): {status: number; text: string} | undefined {\n let e = error\n for (let depth = 0; depth < 10 && e && typeof e === 'object'; depth++) {\n const {status, data, cause} = e as {status?: unknown; data?: {text?: unknown}; cause?: unknown}\n if (typeof status === 'number') {\n const detail = serverMessage(typeof data?.text === 'string' ? data.text : messageOf(e))\n return {status, text: detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}`}\n }\n e = cause\n }\n return undefined\n}\n\nfunction messageOf(error: unknown) {\n const message = (error as {message?: unknown} | undefined)?.message\n return typeof message === 'string' ? message : String(error)\n}\n\nfunction serverMessage(text: string) {\n try {\n const body = JSON.parse(text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1))\n const message = body?.error?.message ?? body?.message ?? body?.error\n return typeof message === 'string' ? message : undefined\n } catch {\n return undefined\n }\n}\n","/** @public */\nexport interface SanityContextOptions {\n /** The Context MCP endpoint URL. */\n url: string\n /** An organization API token with Context access. */\n token: string\n}\n\nexport function validateOptions({url, token}: SanityContextOptions): void {\n if (!url) throw new Error('Sanity Context needs a url: the Context MCP endpoint URL.')\n if (!token)\n throw new Error('Sanity Context needs a token: an organization API token with Context access.')\n // The token goes in a header, so a plain http URL would send it in clear text.\n if (!URL.canParse(url) || new URL(url).protocol !== 'https:')\n throw new Error('Sanity Context needs an https URL.')\n}\n","import {MCPAdapter, ToolException} from '@langchain/mcp-adapters'\nimport {type AgentMiddleware, createMiddleware, ToolMessage} from 'langchain'\n\nimport {connectionError, describeError, httpError} from './describeError'\nimport {type SanityContextOptions, validateOptions} from './options'\n\n/** @public */\nexport interface SanityContextLangChain {\n /**\n * Pass to `createAgent({middleware: [...]})` as the first entry, so other middleware sees the\n * Sanity tools. Before every model call it lists the endpoint's current tools, one request to the\n * endpoint per step, and the call fails if they can't be listed.\n *\n * Errors from the Sanity tools go to the model. Like any middleware that wraps tool calls, it\n * makes LangChain rethrow errors from the agent's own tools; add LangChain's\n * `toolErrorMiddleware` to send those to the model instead.\n */\n middleware: AgentMiddleware\n /** Closes the connection to the endpoint. Optional: the process exits without it. */\n close: () => Promise<void>\n}\n\n/**\n * Connects a LangChain agent to a Context MCP endpoint. Nothing is fetched until the agent runs.\n * Create one per endpoint and token, and reuse it across runs.\n *\n * @public\n */\nexport function createSanityContext(options: SanityContextOptions): SanityContextLangChain {\n validateOptions(options)\n const {url, token} = options\n const client = new MCPAdapter({\n prefixToolNameWithServerName: false,\n servers: {\n sanity: {\n transport: 'http',\n url,\n headers: {Authorization: `Bearer ${token}`},\n // The endpoint speaks the initialize handshake over streamable HTTP. Probing for newer\n // protocols and falling back to SSE costs requests and hides a 404 behind the SSE error.\n mode: 'legacy',\n automaticSSEFallback: false,\n },\n },\n })\n const listTools = async () => {\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n const tools = await Promise.race([\n client.listTools(),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('Timed out after 10 seconds')), 10_000)\n }),\n ])\n // LangChain's own message for an invalid input then names the field and the rule it breaks.\n for (const tool of tools) tool.verboseParsingErrors = true\n return tools\n } catch (error) {\n throw connectionError(error)\n } finally {\n clearTimeout(timer)\n }\n }\n const warnedCollisions = new Set<string>()\n let shown: Map<string, Awaited<ReturnType<typeof listTools>>[number]> | undefined\n\n const middleware = createMiddleware({\n name: 'SanityContext',\n wrapModelCall: async (request, handler) => {\n // LangChain rejects a middleware tool that shares a name with one of the agent's own tools.\n const taken = new Set(request.tools.map((t) => t.name))\n const tools = (await listTools()).filter((tool) => {\n if (!taken.has(tool.name)) return true\n if (!warnedCollisions.has(tool.name)) {\n warnedCollisions.add(tool.name)\n console.warn(\n `[sanity-context] Skipping the Sanity Context tool \"${tool.name}\": the agent already has a tool with that name.`,\n )\n }\n return false\n })\n shown = new Map(tools.map((tool) => [tool.name, tool]))\n return handler({...request, tools: [...request.tools, ...tools]})\n },\n wrapToolCall: async (request, handler) => {\n // LangChain only knows the agent's own tools, so run the Sanity tool the model was shown. A run\n // resumed in a new process has seen no model call yet, so list the tools then. Any other name,\n // such as a tool another middleware adds, goes on to the next handler.\n if (request.tool) return handler(request)\n const name = request.toolCall.name\n // LangChain rethrows errors from tools a middleware runs, which would end the run.\n const toolError = (content: string) =>\n new ToolMessage({\n content,\n tool_call_id: request.toolCall.id ?? '',\n name,\n status: 'error',\n })\n if (!shown) {\n try {\n shown = new Map((await listTools()).map((tool) => [tool.name, tool]))\n } catch (error) {\n return toolError((error as Error).message)\n }\n }\n const tool = shown.get(name)\n if (!tool) return handler(request)\n try {\n return await handler({...request, tool})\n } catch (error) {\n if (!(error instanceof ToolException)) throw error\n const http = httpError(error)?.text\n return toolError(http ? `Error calling tool ${name}: ${http}` : describeError(error))\n }\n },\n })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IACF;AAAA,EAAA,CACD,GAEmB,OAAO,MAAM,OAAO,QAAM;AAChD;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,70 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/context-langchain",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Sanity Context for LangChain agents",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"sanity",
|
|
7
|
+
"sanity-context",
|
|
8
|
+
"langchain",
|
|
9
|
+
"middleware",
|
|
10
|
+
"mcp"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://www.sanity.io/docs/context/connect-langchain",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+ssh://git@github.com/sanity-io/context.git",
|
|
16
|
+
"directory": "packages/langchain"
|
|
17
|
+
},
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"author": "Sanity.io <hello@sanity.io>",
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"type": "module",
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"source": "./src/index.ts",
|
|
25
|
+
"import": "./dist/index.js",
|
|
26
|
+
"default": "./dist/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./package.json": "./package.json"
|
|
29
|
+
},
|
|
30
|
+
"main": "./dist/index.js",
|
|
31
|
+
"module": "./dist/index.js",
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"src",
|
|
36
|
+
"!src/**/*.test.ts"
|
|
37
|
+
],
|
|
38
|
+
"browserslist": "extends @sanity/browserslist-config",
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@langchain/core": "^1.4.0",
|
|
41
|
+
"@langchain/mcp-adapters": "^2.0.3",
|
|
42
|
+
"@sanity/pkg-utils": "^10.4.13",
|
|
43
|
+
"@sanity/tsconfig": "^2.2.1",
|
|
44
|
+
"@vitest/coverage-v8": "^4.1.11",
|
|
45
|
+
"langchain": "^1.6.5",
|
|
46
|
+
"typescript": "^5",
|
|
47
|
+
"vitest": "^4.1.11",
|
|
48
|
+
"@repo/eslint-config": "0.0.0"
|
|
49
|
+
},
|
|
50
|
+
"peerDependencies": {
|
|
51
|
+
"@langchain/mcp-adapters": "^2.0.3",
|
|
52
|
+
"langchain": "^1.6.0"
|
|
53
|
+
},
|
|
54
|
+
"engines": {
|
|
55
|
+
"node": ">=20.19 <22 || >=22.12"
|
|
56
|
+
},
|
|
57
|
+
"publishConfig": {
|
|
58
|
+
"access": "public"
|
|
59
|
+
},
|
|
60
|
+
"scripts": {
|
|
61
|
+
"build": "pkg build --strict --clean --check",
|
|
62
|
+
"check:lint": "eslint .",
|
|
63
|
+
"check:lint:fix": "eslint . --fix",
|
|
64
|
+
"check:types": "tsc --noEmit",
|
|
65
|
+
"dev": "pkg-utils watch",
|
|
66
|
+
"test": "vitest run --typecheck",
|
|
67
|
+
"test:unit": "vitest --typecheck",
|
|
68
|
+
"test:unit:coverage": "vitest run --coverage"
|
|
69
|
+
}
|
|
6
70
|
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import {MCPAdapter, ToolException} from '@langchain/mcp-adapters'
|
|
2
|
+
import {type AgentMiddleware, createMiddleware, ToolMessage} from 'langchain'
|
|
3
|
+
|
|
4
|
+
import {connectionError, describeError, httpError} from './describeError'
|
|
5
|
+
import {type SanityContextOptions, validateOptions} from './options'
|
|
6
|
+
|
|
7
|
+
/** @public */
|
|
8
|
+
export interface SanityContextLangChain {
|
|
9
|
+
/**
|
|
10
|
+
* Pass to `createAgent({middleware: [...]})` as the first entry, so other middleware sees the
|
|
11
|
+
* Sanity tools. Before every model call it lists the endpoint's current tools, one request to the
|
|
12
|
+
* endpoint per step, and the call fails if they can't be listed.
|
|
13
|
+
*
|
|
14
|
+
* Errors from the Sanity tools go to the model. Like any middleware that wraps tool calls, it
|
|
15
|
+
* makes LangChain rethrow errors from the agent's own tools; add LangChain's
|
|
16
|
+
* `toolErrorMiddleware` to send those to the model instead.
|
|
17
|
+
*/
|
|
18
|
+
middleware: AgentMiddleware
|
|
19
|
+
/** Closes the connection to the endpoint. Optional: the process exits without it. */
|
|
20
|
+
close: () => Promise<void>
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Connects a LangChain agent to a Context MCP endpoint. Nothing is fetched until the agent runs.
|
|
25
|
+
* Create one per endpoint and token, and reuse it across runs.
|
|
26
|
+
*
|
|
27
|
+
* @public
|
|
28
|
+
*/
|
|
29
|
+
export function createSanityContext(options: SanityContextOptions): SanityContextLangChain {
|
|
30
|
+
validateOptions(options)
|
|
31
|
+
const {url, token} = options
|
|
32
|
+
const client = new MCPAdapter({
|
|
33
|
+
prefixToolNameWithServerName: false,
|
|
34
|
+
servers: {
|
|
35
|
+
sanity: {
|
|
36
|
+
transport: 'http',
|
|
37
|
+
url,
|
|
38
|
+
headers: {Authorization: `Bearer ${token}`},
|
|
39
|
+
// The endpoint speaks the initialize handshake over streamable HTTP. Probing for newer
|
|
40
|
+
// protocols and falling back to SSE costs requests and hides a 404 behind the SSE error.
|
|
41
|
+
mode: 'legacy',
|
|
42
|
+
automaticSSEFallback: false,
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
})
|
|
46
|
+
const listTools = async () => {
|
|
47
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
48
|
+
try {
|
|
49
|
+
const tools = await Promise.race([
|
|
50
|
+
client.listTools(),
|
|
51
|
+
new Promise<never>((_, reject) => {
|
|
52
|
+
timer = setTimeout(() => reject(new Error('Timed out after 10 seconds')), 10_000)
|
|
53
|
+
}),
|
|
54
|
+
])
|
|
55
|
+
// LangChain's own message for an invalid input then names the field and the rule it breaks.
|
|
56
|
+
for (const tool of tools) tool.verboseParsingErrors = true
|
|
57
|
+
return tools
|
|
58
|
+
} catch (error) {
|
|
59
|
+
throw connectionError(error)
|
|
60
|
+
} finally {
|
|
61
|
+
clearTimeout(timer)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const warnedCollisions = new Set<string>()
|
|
65
|
+
let shown: Map<string, Awaited<ReturnType<typeof listTools>>[number]> | undefined
|
|
66
|
+
|
|
67
|
+
const middleware = createMiddleware({
|
|
68
|
+
name: 'SanityContext',
|
|
69
|
+
wrapModelCall: async (request, handler) => {
|
|
70
|
+
// LangChain rejects a middleware tool that shares a name with one of the agent's own tools.
|
|
71
|
+
const taken = new Set(request.tools.map((t) => t.name))
|
|
72
|
+
const tools = (await listTools()).filter((tool) => {
|
|
73
|
+
if (!taken.has(tool.name)) return true
|
|
74
|
+
if (!warnedCollisions.has(tool.name)) {
|
|
75
|
+
warnedCollisions.add(tool.name)
|
|
76
|
+
console.warn(
|
|
77
|
+
`[sanity-context] Skipping the Sanity Context tool "${tool.name}": the agent already has a tool with that name.`,
|
|
78
|
+
)
|
|
79
|
+
}
|
|
80
|
+
return false
|
|
81
|
+
})
|
|
82
|
+
shown = new Map(tools.map((tool) => [tool.name, tool]))
|
|
83
|
+
return handler({...request, tools: [...request.tools, ...tools]})
|
|
84
|
+
},
|
|
85
|
+
wrapToolCall: async (request, handler) => {
|
|
86
|
+
// LangChain only knows the agent's own tools, so run the Sanity tool the model was shown. A run
|
|
87
|
+
// resumed in a new process has seen no model call yet, so list the tools then. Any other name,
|
|
88
|
+
// such as a tool another middleware adds, goes on to the next handler.
|
|
89
|
+
if (request.tool) return handler(request)
|
|
90
|
+
const name = request.toolCall.name
|
|
91
|
+
// LangChain rethrows errors from tools a middleware runs, which would end the run.
|
|
92
|
+
const toolError = (content: string) =>
|
|
93
|
+
new ToolMessage({
|
|
94
|
+
content,
|
|
95
|
+
tool_call_id: request.toolCall.id ?? '',
|
|
96
|
+
name,
|
|
97
|
+
status: 'error',
|
|
98
|
+
})
|
|
99
|
+
if (!shown) {
|
|
100
|
+
try {
|
|
101
|
+
shown = new Map((await listTools()).map((tool) => [tool.name, tool]))
|
|
102
|
+
} catch (error) {
|
|
103
|
+
return toolError((error as Error).message)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const tool = shown.get(name)
|
|
107
|
+
if (!tool) return handler(request)
|
|
108
|
+
try {
|
|
109
|
+
return await handler({...request, tool})
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if (!(error instanceof ToolException)) throw error
|
|
112
|
+
const http = httpError(error)?.text
|
|
113
|
+
return toolError(http ? `Error calling tool ${name}: ${http}` : describeError(error))
|
|
114
|
+
}
|
|
115
|
+
},
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
return {middleware, close: () => client.close()}
|
|
119
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One line describing a failed MCP request. An HTTP error becomes its status and the server's own
|
|
3
|
+
* message, without the raw response body, which can be a gateway's HTML page.
|
|
4
|
+
*/
|
|
5
|
+
export function describeError(error: unknown): string {
|
|
6
|
+
try {
|
|
7
|
+
return httpError(error)?.text ?? messageOf(error).split('\n')[0] ?? ''
|
|
8
|
+
} catch {
|
|
9
|
+
return 'Unknown error'
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** The error to throw when the endpoint's tools can't be listed. */
|
|
14
|
+
export function connectionError(error: unknown): Error {
|
|
15
|
+
const http = httpError(error)
|
|
16
|
+
const detail = http?.text ?? describeError(error)
|
|
17
|
+
const message =
|
|
18
|
+
http?.status === 401 || http?.status === 403
|
|
19
|
+
? `Sanity Context rejected the token (${detail}). Use an organization API token with Context access.`
|
|
20
|
+
: `Could not connect to Sanity Context: ${detail}`
|
|
21
|
+
return new Error(message, {cause: error})
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The status and server message of the first HTTP error in the cause chain, if there is one. */
|
|
25
|
+
export function httpError(error: unknown): {status: number; text: string} | undefined {
|
|
26
|
+
try {
|
|
27
|
+
return findHttpError(error)
|
|
28
|
+
} catch {
|
|
29
|
+
return undefined
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function findHttpError(error: unknown): {status: number; text: string} | undefined {
|
|
34
|
+
let e = error
|
|
35
|
+
for (let depth = 0; depth < 10 && e && typeof e === 'object'; depth++) {
|
|
36
|
+
const {status, data, cause} = e as {status?: unknown; data?: {text?: unknown}; cause?: unknown}
|
|
37
|
+
if (typeof status === 'number') {
|
|
38
|
+
const detail = serverMessage(typeof data?.text === 'string' ? data.text : messageOf(e))
|
|
39
|
+
return {status, text: detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}`}
|
|
40
|
+
}
|
|
41
|
+
e = cause
|
|
42
|
+
}
|
|
43
|
+
return undefined
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function messageOf(error: unknown) {
|
|
47
|
+
const message = (error as {message?: unknown} | undefined)?.message
|
|
48
|
+
return typeof message === 'string' ? message : String(error)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function serverMessage(text: string) {
|
|
52
|
+
try {
|
|
53
|
+
const body = JSON.parse(text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1))
|
|
54
|
+
const message = body?.error?.message ?? body?.message ?? body?.error
|
|
55
|
+
return typeof message === 'string' ? message : undefined
|
|
56
|
+
} catch {
|
|
57
|
+
return undefined
|
|
58
|
+
}
|
|
59
|
+
}
|
package/src/index.ts
ADDED
package/src/options.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** @public */
|
|
2
|
+
export interface SanityContextOptions {
|
|
3
|
+
/** The Context MCP endpoint URL. */
|
|
4
|
+
url: string
|
|
5
|
+
/** An organization API token with Context access. */
|
|
6
|
+
token: string
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function validateOptions({url, token}: SanityContextOptions): void {
|
|
10
|
+
if (!url) throw new Error('Sanity Context needs a url: the Context MCP endpoint URL.')
|
|
11
|
+
if (!token)
|
|
12
|
+
throw new Error('Sanity Context needs a token: an organization API token with Context access.')
|
|
13
|
+
// The token goes in a header, so a plain http URL would send it in clear text.
|
|
14
|
+
if (!URL.canParse(url) || new URL(url).protocol !== 'https:')
|
|
15
|
+
throw new Error('Sanity Context needs an https URL.')
|
|
16
|
+
}
|