@sanity/context-langchain 0.0.0-stage → 0.2.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 CHANGED
@@ -1,3 +1,45 @@
1
- # Temporary Holding Version
1
+ # @sanity/context-langchain
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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. Each run loads the endpoint's initial context once and adds it to the system prompt, so the model doesn't spend a tool call loading it.
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
+ - The middleware lists the endpoint's tools before every model call. It keeps the initial context in the run's state, so a checkpointer saves it with the run.
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
+ - If the initial context can't be loaded, the middleware logs a warning and the run goes ahead without it. The `initial_context` tool stays available as a safety net.
43
+ - Tool results contain your content, so anyone who can edit that content can influence what the agent does.
44
+
45
+ See the [Sanity Context guide for LangChain](https://www.sanity.io/docs/context/connect-langchain) for setting up an endpoint and a token.
@@ -0,0 +1,36 @@
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. It loads the endpoint's initial context once per run and adds it to the system
16
+ * prompt, and lists the endpoint's current tools before every model call. The call fails if the
17
+ * tools can't be listed. The `initial_context` tool stays available as a safety net.
18
+ *
19
+ * Errors from the Sanity tools go to the model. Like any middleware that wraps tool calls, it
20
+ * makes LangChain rethrow errors from the agent's own tools; add LangChain's
21
+ * `toolErrorMiddleware` to send those to the model instead.
22
+ */
23
+ middleware: AgentMiddleware
24
+ /** Closes the connection to the endpoint. Optional: the process exits without it. */
25
+ close: () => Promise<void>
26
+ }
27
+
28
+ /** @public */
29
+ export declare interface SanityContextOptions {
30
+ /** The Context MCP endpoint URL. */
31
+ url: string
32
+ /** An organization API token with Context access. */
33
+ token: string
34
+ }
35
+
36
+ export {}
package/dist/index.js ADDED
@@ -0,0 +1,159 @@
1
+ import { MCPAdapter, ToolException } from "@langchain/mcp-adapters";
2
+ import { createMiddleware, ToolMessage } from "langchain";
3
+ import { z } from "zod";
4
+ var version = "0.2.0";
5
+ function describeError(error) {
6
+ try {
7
+ return httpError(error)?.text ?? messageOf(error).split(`
8
+ `)[0] ?? "";
9
+ } catch {
10
+ return "Unknown error";
11
+ }
12
+ }
13
+ function connectionError(error) {
14
+ 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}`;
15
+ return new Error(message, { cause: error });
16
+ }
17
+ function httpError(error) {
18
+ try {
19
+ return findHttpError(error);
20
+ } catch {
21
+ return;
22
+ }
23
+ }
24
+ function findHttpError(error) {
25
+ let e = error;
26
+ for (let depth = 0; depth < 10 && e && typeof e == "object"; depth++) {
27
+ const { status, data, cause } = e;
28
+ if (typeof status == "number") {
29
+ const detail = serverMessage(typeof data?.text == "string" ? data.text : messageOf(e));
30
+ return { status, text: detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}` };
31
+ }
32
+ e = cause;
33
+ }
34
+ }
35
+ function messageOf(error) {
36
+ const message = error?.message;
37
+ return typeof message == "string" ? message : String(error);
38
+ }
39
+ function serverMessage(text) {
40
+ try {
41
+ const body = JSON.parse(text.slice(text.indexOf("{"), text.lastIndexOf("}") + 1)), message = body?.error?.message ?? body?.message ?? body?.error;
42
+ return typeof message == "string" ? message : void 0;
43
+ } catch {
44
+ return;
45
+ }
46
+ }
47
+ function validateOptions({ url, token }) {
48
+ if (!url) throw new Error("Sanity Context needs a url: the Context MCP endpoint URL.");
49
+ if (!token)
50
+ throw new Error("Sanity Context needs a token: an organization API token with Context access.");
51
+ if (!URL.canParse(url) || new URL(url).protocol !== "https:")
52
+ throw new Error("Sanity Context needs an https URL.");
53
+ }
54
+ function createSanityContext(options) {
55
+ validateOptions(options);
56
+ const { url, token } = options, client = new MCPAdapter({
57
+ prefixToolNameWithServerName: !1,
58
+ servers: {
59
+ sanity: {
60
+ transport: "http",
61
+ url,
62
+ headers: { Authorization: `Bearer ${token}` },
63
+ // The endpoint speaks the initialize handshake over streamable HTTP. Probing for newer
64
+ // protocols and falling back to SSE costs requests and hides a 404 behind the SSE error.
65
+ mode: "legacy",
66
+ automaticSSEFallback: !1
67
+ }
68
+ }
69
+ }), listTools = async () => {
70
+ let timer;
71
+ try {
72
+ const tools = await Promise.race([
73
+ client.listTools(),
74
+ new Promise((_, reject) => {
75
+ timer = setTimeout(() => reject(new Error("Timed out after 10 seconds")), 1e4);
76
+ })
77
+ ]);
78
+ for (const tool of tools) tool.verboseParsingErrors = !0;
79
+ return tools;
80
+ } catch (error) {
81
+ throw connectionError(error);
82
+ } finally {
83
+ clearTimeout(timer);
84
+ }
85
+ }, initialContextUrl = new URL(url);
86
+ initialContextUrl.pathname = `${initialContextUrl.pathname.replace(/\/$/, "")}/initial-context`;
87
+ let warnedInitialContext = !1;
88
+ const fetchInitialContext = async (signal) => {
89
+ try {
90
+ const res = await fetch(initialContextUrl, {
91
+ headers: {
92
+ Authorization: `Bearer ${token}`,
93
+ "User-Agent": `sanity-context-langchain/${version}`
94
+ },
95
+ signal: AbortSignal.any([AbortSignal.timeout(1e4), ...signal ? [signal] : []])
96
+ });
97
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
98
+ const text = await res.text();
99
+ if (!text) throw new Error("empty response");
100
+ return warnedInitialContext = !1, text;
101
+ } catch (error) {
102
+ if (signal?.aborted) throw error;
103
+ return warnedInitialContext || (warnedInitialContext = !0, console.warn(
104
+ `[sanity-context] Could not load the initial context: ${error.message}`
105
+ )), null;
106
+ }
107
+ }, warnedCollisions = /* @__PURE__ */ new Set();
108
+ let shown;
109
+ return { middleware: createMiddleware({
110
+ name: "SanityContext",
111
+ // Private, so it stays out of the agent's input and output.
112
+ stateSchema: z.object({ _sanityInitialContext: z.string().nullable().optional() }),
113
+ beforeAgent: async (_state, runtime) => ({
114
+ _sanityInitialContext: await fetchInitialContext(runtime.signal)
115
+ }),
116
+ wrapModelCall: async (request, handler) => {
117
+ const taken = new Set(request.tools.map((t) => t.name)), initialContext = request.state._sanityInitialContext, tools = (await listTools()).filter((tool) => taken.has(tool.name) ? (warnedCollisions.has(tool.name) || (warnedCollisions.add(tool.name), console.warn(
118
+ `[sanity-context] Skipping the Sanity Context tool "${tool.name}": the agent already has a tool with that name.`
119
+ )), !1) : !0);
120
+ return shown = new Map(tools.map((tool) => [tool.name, tool])), handler({
121
+ ...request,
122
+ tools: [...request.tools, ...tools],
123
+ ...initialContext && {
124
+ systemMessage: request.systemMessage.concat(`
125
+
126
+ ${initialContext}`)
127
+ }
128
+ });
129
+ },
130
+ wrapToolCall: async (request, handler) => {
131
+ if (request.tool) return handler(request);
132
+ const name = request.toolCall.name, toolError = (content) => new ToolMessage({
133
+ content,
134
+ tool_call_id: request.toolCall.id ?? "",
135
+ name,
136
+ status: "error"
137
+ });
138
+ if (!shown)
139
+ try {
140
+ shown = new Map((await listTools()).map((tool2) => [tool2.name, tool2]));
141
+ } catch (error) {
142
+ return toolError(error.message);
143
+ }
144
+ const tool = shown.get(name);
145
+ if (!tool) return handler(request);
146
+ try {
147
+ return await handler({ ...request, tool });
148
+ } catch (error) {
149
+ if (!(error instanceof ToolException)) throw error;
150
+ const http = httpError(error)?.text;
151
+ return toolError(http ? `Error calling tool ${name}: ${http}` : describeError(error));
152
+ }
153
+ }
154
+ }), close: () => client.close() };
155
+ }
156
+ export {
157
+ createSanityContext
158
+ };
159
+ //# 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'\nimport {z} from 'zod'\n\nimport {version} from '../package.json' with {type: 'json'}\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. It loads the endpoint's initial context once per run and adds it to the system\n * prompt, and lists the endpoint's current tools before every model call. The call fails if the\n * tools can't be listed. The `initial_context` tool stays available as a safety net.\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 initialContextUrl = new URL(url)\n initialContextUrl.pathname = `${initialContextUrl.pathname.replace(/\\/$/, '')}/initial-context`\n let warnedInitialContext = false\n const fetchInitialContext = async (signal: AbortSignal | undefined) => {\n try {\n const res = await fetch(initialContextUrl, {\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'User-Agent': `sanity-context-langchain/${version}`,\n },\n signal: AbortSignal.any([AbortSignal.timeout(10_000), ...(signal ? [signal] : [])]),\n })\n if (!res.ok) throw new Error(`HTTP ${res.status}`)\n const text = await res.text()\n if (!text) throw new Error('empty response')\n warnedInitialContext = false\n return text\n } catch (error) {\n if (signal?.aborted) throw error\n if (!warnedInitialContext) {\n warnedInitialContext = true\n console.warn(\n `[sanity-context] Could not load the initial context: ${(error as Error).message}`,\n )\n }\n return null\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 // Private, so it stays out of the agent's input and output.\n stateSchema: z.object({_sanityInitialContext: z.string().nullable().optional()}),\n beforeAgent: async (_state, runtime) => ({\n _sanityInitialContext: await fetchInitialContext(runtime.signal),\n }),\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 initialContext = request.state._sanityInitialContext\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({\n ...request,\n tools: [...request.tools, ...tools],\n ...(initialContext && {\n systemMessage: request.systemMessage.concat(`\\n\\n${initialContext}`),\n }),\n })\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 })\n\n return {middleware, close: () => client.close()}\n}\n"],"names":["tool"],"mappings":";;;;AAIO,SAAS,cAAc,OAAwB;AACpD,MAAI;AACF,WAAO,UAAU,KAAK,GAAG,QAAQ,UAAU,KAAK,EAAE,MAAM;AAAA,CAAI,EAAE,CAAC,KAAK;AAAA,EACtE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,gBAAgB,OAAuB;AACrD,QAAM,OAAO,UAAU,KAAK,GACtB,SAAS,MAAM,QAAQ,cAAc,KAAK,GAC1C,UACJ,MAAM,WAAW,OAAO,MAAM,WAAW,MACrC,sCAAsC,MAAM,0DAC5C,wCAAwC,MAAM;AACpD,SAAO,IAAI,MAAM,SAAS,EAAC,OAAO,OAAM;AAC1C;AAGO,SAAS,UAAU,OAA4D;AACpF,MAAI;AACF,WAAO,cAAc,KAAK;AAAA,EAC5B,QAAQ;AACN;AAAA,EACF;AACF;AAEA,SAAS,cAAc,OAA4D;AACjF,MAAI,IAAI;AACR,WAAS,QAAQ,GAAG,QAAQ,MAAM,KAAK,OAAO,KAAM,UAAU,SAAS;AACrE,UAAM,EAAC,QAAQ,MAAM,MAAA,IAAS;AAC9B,QAAI,OAAO,UAAW,UAAU;AAC9B,YAAM,SAAS,cAAc,OAAO,MAAM,QAAS,WAAW,KAAK,OAAO,UAAU,CAAC,CAAC;AACtF,aAAO,EAAC,QAAQ,MAAM,SAAS,QAAQ,MAAM,KAAK,MAAM,KAAK,QAAQ,MAAM,GAAA;AAAA,IAC7E;AACA,QAAI;AAAA,EACN;AAEF;AAEA,SAAS,UAAU,OAAgB;AACjC,QAAM,UAAW,OAA2C;AAC5D,SAAO,OAAO,WAAY,WAAW,UAAU,OAAO,KAAK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O,UAAU,OAAO,sBAAsB,IAAI,KAAK,IAAI,KAAK,cAAc,KAAK,CAAC;AAAA,MACtF;AAAA,IACF;AAAA,EAAA,CACD,GAEmB,OAAO,MAAM,OAAO,QAAM;AAChD;"}
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "@sanity/context-langchain",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.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
+ "dependencies": {
40
+ "zod": "^4.3.6"
41
+ },
42
+ "devDependencies": {
43
+ "@langchain/core": "^1.4.0",
44
+ "@langchain/mcp-adapters": "^2.0.3",
45
+ "@sanity/pkg-utils": "^10.4.13",
46
+ "@sanity/tsconfig": "^2.2.1",
47
+ "@vitest/coverage-v8": "^4.1.11",
48
+ "langchain": "^1.6.5",
49
+ "typescript": "^5",
50
+ "vitest": "^4.1.11",
51
+ "@repo/eslint-config": "0.0.0"
52
+ },
53
+ "peerDependencies": {
54
+ "@langchain/mcp-adapters": "^2.0.3",
55
+ "langchain": "^1.6.0"
56
+ },
57
+ "engines": {
58
+ "node": ">=20.19 <22 || >=22.12"
59
+ },
60
+ "publishConfig": {
61
+ "access": "public"
62
+ },
63
+ "scripts": {
64
+ "build": "pkg build --strict --clean --check",
65
+ "check:lint": "eslint .",
66
+ "check:lint:fix": "eslint . --fix",
67
+ "check:types": "tsc --noEmit",
68
+ "dev": "pkg-utils watch",
69
+ "test": "vitest run --typecheck",
70
+ "test:unit": "vitest --typecheck",
71
+ "test:unit:coverage": "vitest run --coverage"
72
+ }
6
73
  }
@@ -0,0 +1,162 @@
1
+ import {MCPAdapter, ToolException} from '@langchain/mcp-adapters'
2
+ import {type AgentMiddleware, createMiddleware, ToolMessage} from 'langchain'
3
+ import {z} from 'zod'
4
+
5
+ import {version} from '../package.json' with {type: 'json'}
6
+ import {connectionError, describeError, httpError} from './describeError'
7
+ import {type SanityContextOptions, validateOptions} from './options'
8
+
9
+ /** @public */
10
+ export interface SanityContextLangChain {
11
+ /**
12
+ * Pass to `createAgent({middleware: [...]})` as the first entry, so other middleware sees the
13
+ * Sanity tools. It loads the endpoint's initial context once per run and adds it to the system
14
+ * prompt, and lists the endpoint's current tools before every model call. The call fails if the
15
+ * tools can't be listed. The `initial_context` tool stays available as a safety net.
16
+ *
17
+ * Errors from the Sanity tools go to the model. Like any middleware that wraps tool calls, it
18
+ * makes LangChain rethrow errors from the agent's own tools; add LangChain's
19
+ * `toolErrorMiddleware` to send those to the model instead.
20
+ */
21
+ middleware: AgentMiddleware
22
+ /** Closes the connection to the endpoint. Optional: the process exits without it. */
23
+ close: () => Promise<void>
24
+ }
25
+
26
+ /**
27
+ * Connects a LangChain agent to a Context MCP endpoint. Nothing is fetched until the agent runs.
28
+ * Create one per endpoint and token, and reuse it across runs.
29
+ *
30
+ * @public
31
+ */
32
+ export function createSanityContext(options: SanityContextOptions): SanityContextLangChain {
33
+ validateOptions(options)
34
+ const {url, token} = options
35
+ const client = new MCPAdapter({
36
+ prefixToolNameWithServerName: false,
37
+ servers: {
38
+ sanity: {
39
+ transport: 'http',
40
+ url,
41
+ headers: {Authorization: `Bearer ${token}`},
42
+ // The endpoint speaks the initialize handshake over streamable HTTP. Probing for newer
43
+ // protocols and falling back to SSE costs requests and hides a 404 behind the SSE error.
44
+ mode: 'legacy',
45
+ automaticSSEFallback: false,
46
+ },
47
+ },
48
+ })
49
+ const listTools = async () => {
50
+ let timer: ReturnType<typeof setTimeout> | undefined
51
+ try {
52
+ const tools = await Promise.race([
53
+ client.listTools(),
54
+ new Promise<never>((_, reject) => {
55
+ timer = setTimeout(() => reject(new Error('Timed out after 10 seconds')), 10_000)
56
+ }),
57
+ ])
58
+ // LangChain's own message for an invalid input then names the field and the rule it breaks.
59
+ for (const tool of tools) tool.verboseParsingErrors = true
60
+ return tools
61
+ } catch (error) {
62
+ throw connectionError(error)
63
+ } finally {
64
+ clearTimeout(timer)
65
+ }
66
+ }
67
+ const initialContextUrl = new URL(url)
68
+ initialContextUrl.pathname = `${initialContextUrl.pathname.replace(/\/$/, '')}/initial-context`
69
+ let warnedInitialContext = false
70
+ const fetchInitialContext = async (signal: AbortSignal | undefined) => {
71
+ try {
72
+ const res = await fetch(initialContextUrl, {
73
+ headers: {
74
+ 'Authorization': `Bearer ${token}`,
75
+ 'User-Agent': `sanity-context-langchain/${version}`,
76
+ },
77
+ signal: AbortSignal.any([AbortSignal.timeout(10_000), ...(signal ? [signal] : [])]),
78
+ })
79
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
80
+ const text = await res.text()
81
+ if (!text) throw new Error('empty response')
82
+ warnedInitialContext = false
83
+ return text
84
+ } catch (error) {
85
+ if (signal?.aborted) throw error
86
+ if (!warnedInitialContext) {
87
+ warnedInitialContext = true
88
+ console.warn(
89
+ `[sanity-context] Could not load the initial context: ${(error as Error).message}`,
90
+ )
91
+ }
92
+ return null
93
+ }
94
+ }
95
+ const warnedCollisions = new Set<string>()
96
+ let shown: Map<string, Awaited<ReturnType<typeof listTools>>[number]> | undefined
97
+
98
+ const middleware = createMiddleware({
99
+ name: 'SanityContext',
100
+ // Private, so it stays out of the agent's input and output.
101
+ stateSchema: z.object({_sanityInitialContext: z.string().nullable().optional()}),
102
+ beforeAgent: async (_state, runtime) => ({
103
+ _sanityInitialContext: await fetchInitialContext(runtime.signal),
104
+ }),
105
+ wrapModelCall: async (request, handler) => {
106
+ // LangChain rejects a middleware tool that shares a name with one of the agent's own tools.
107
+ const taken = new Set(request.tools.map((t) => t.name))
108
+ const initialContext = request.state._sanityInitialContext
109
+ const tools = (await listTools()).filter((tool) => {
110
+ if (!taken.has(tool.name)) return true
111
+ if (!warnedCollisions.has(tool.name)) {
112
+ warnedCollisions.add(tool.name)
113
+ console.warn(
114
+ `[sanity-context] Skipping the Sanity Context tool "${tool.name}": the agent already has a tool with that name.`,
115
+ )
116
+ }
117
+ return false
118
+ })
119
+ shown = new Map(tools.map((tool) => [tool.name, tool]))
120
+ return handler({
121
+ ...request,
122
+ tools: [...request.tools, ...tools],
123
+ ...(initialContext && {
124
+ systemMessage: request.systemMessage.concat(`\n\n${initialContext}`),
125
+ }),
126
+ })
127
+ },
128
+ wrapToolCall: async (request, handler) => {
129
+ // LangChain only knows the agent's own tools, so run the Sanity tool the model was shown. A run
130
+ // resumed in a new process has seen no model call yet, so list the tools then. Any other name,
131
+ // such as a tool another middleware adds, goes on to the next handler.
132
+ if (request.tool) return handler(request)
133
+ const name = request.toolCall.name
134
+ // LangChain rethrows errors from tools a middleware runs, which would end the run.
135
+ const toolError = (content: string) =>
136
+ new ToolMessage({
137
+ content,
138
+ tool_call_id: request.toolCall.id ?? '',
139
+ name,
140
+ status: 'error',
141
+ })
142
+ if (!shown) {
143
+ try {
144
+ shown = new Map((await listTools()).map((tool) => [tool.name, tool]))
145
+ } catch (error) {
146
+ return toolError((error as Error).message)
147
+ }
148
+ }
149
+ const tool = shown.get(name)
150
+ if (!tool) return handler(request)
151
+ try {
152
+ return await handler({...request, tool})
153
+ } catch (error) {
154
+ if (!(error instanceof ToolException)) throw error
155
+ const http = httpError(error)?.text
156
+ return toolError(http ? `Error calling tool ${name}: ${http}` : describeError(error))
157
+ }
158
+ },
159
+ })
160
+
161
+ return {middleware, close: () => client.close()}
162
+ }
@@ -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
@@ -0,0 +1,3 @@
1
+ export type {SanityContextLangChain} from './createSanityContext'
2
+ export {createSanityContext} from './createSanityContext'
3
+ export type {SanityContextOptions} from './options'
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
+ }