@sanity/context-langchain 0.1.0 → 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 +3 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +39 -2
- package/dist/index.js.map +1 -1
- package/package.json +4 -1
- package/src/createSanityContext.ts +46 -3
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @sanity/context-langchain
|
|
2
2
|
|
|
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.
|
|
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
4
|
|
|
5
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
6
|
|
|
@@ -32,13 +32,14 @@ const agent = createAgent({
|
|
|
32
32
|
```
|
|
33
33
|
|
|
34
34
|
- Requires `langchain` 1.6 or later.
|
|
35
|
-
-
|
|
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
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
37
|
|
|
38
38
|
## Errors
|
|
39
39
|
|
|
40
40
|
- A missing URL or token, or a URL that isn't https, throws when you create the connector.
|
|
41
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.
|
|
42
43
|
- Tool results contain your content, so anyone who can edit that content can influence what the agent does.
|
|
43
44
|
|
|
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.
|
package/dist/index.d.ts
CHANGED
|
@@ -12,8 +12,9 @@ export declare function createSanityContext(options: SanityContextOptions): Sani
|
|
|
12
12
|
export declare interface SanityContextLangChain {
|
|
13
13
|
/**
|
|
14
14
|
* Pass to `createAgent({middleware: [...]})` as the first entry, so other middleware sees the
|
|
15
|
-
* Sanity tools.
|
|
16
|
-
*
|
|
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.
|
|
17
18
|
*
|
|
18
19
|
* Errors from the Sanity tools go to the model. Like any middleware that wraps tool calls, it
|
|
19
20
|
* makes LangChain rethrow errors from the agent's own tools; add LangChain's
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { MCPAdapter, ToolException } from "@langchain/mcp-adapters";
|
|
2
2
|
import { createMiddleware, ToolMessage } from "langchain";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
var version = "0.2.0";
|
|
3
5
|
function describeError(error) {
|
|
4
6
|
try {
|
|
5
7
|
return httpError(error)?.text ?? messageOf(error).split(`
|
|
@@ -80,15 +82,50 @@ function createSanityContext(options) {
|
|
|
80
82
|
} finally {
|
|
81
83
|
clearTimeout(timer);
|
|
82
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
|
+
}
|
|
83
107
|
}, warnedCollisions = /* @__PURE__ */ new Set();
|
|
84
108
|
let shown;
|
|
85
109
|
return { middleware: createMiddleware({
|
|
86
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
|
+
}),
|
|
87
116
|
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(
|
|
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(
|
|
89
118
|
`[sanity-context] Skipping the Sanity Context tool "${tool.name}": the agent already has a tool with that name.`
|
|
90
119
|
)), !1) : !0);
|
|
91
|
-
return shown = new Map(tools.map((tool) => [tool.name, tool])), handler({
|
|
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
|
+
});
|
|
92
129
|
},
|
|
93
130
|
wrapToolCall: async (request, handler) => {
|
|
94
131
|
if (request.tool) return handler(request);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +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 })\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;AAC7D;AAEA,SAAS,cAAc,MAAc;AACnC,MAAI;AACF,UAAM,OAAO,KAAK,MAAM,KAAK,MAAM,KAAK,QAAQ,GAAG,G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AAO,sBAAsB,IAAI,KAAK,IAAI,KAAK,cAAc,KAAK,CAAC;AAAA,MACtF;AAAA,IACF;AAAA,EAAA,CACD,GAEmB,OAAO,MAAM,OAAO,QAAM;AAChD;"}
|
|
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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QACd;AAAA,QACA,cAAc,QAAQ,SAAS,MAAM;AAAA,QACrC;AAAA,QACA,QAAQ;AAAA,MAAA,CACT;AACH,UAAI,CAAC;AACH,YAAI;AACF,kBAAQ,IAAI,KAAK,MAAM,UAAA,GAAa,IAAI,CAACA,UAAS,CAACA,MAAK,MAAMA,KAAI,CAAC,CAAC;AAAA,QACtE,SAAS,OAAO;AACd,iBAAO,UAAW,MAAgB,OAAO;AAAA,QAC3C;AAEF,YAAM,OAAO,MAAM,IAAI,IAAI;AAC3B,UAAI,CAAC,KAAM,QAAO,QAAQ,OAAO;AACjC,UAAI;AACF,eAAO,MAAM,QAAQ,EAAC,GAAG,SAAS,MAAK;AAAA,MACzC,SAAS,OAAO;AACd,YAAI,EAAE,iBAAiB,eAAgB,OAAM;AAC7C,cAAM,OAAO,UAAU,KAAK,GAAG;AAC/B,eAAO,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,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/context-langchain",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Sanity Context for LangChain agents",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -36,6 +36,9 @@
|
|
|
36
36
|
"!src/**/*.test.ts"
|
|
37
37
|
],
|
|
38
38
|
"browserslist": "extends @sanity/browserslist-config",
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"zod": "^4.3.6"
|
|
41
|
+
},
|
|
39
42
|
"devDependencies": {
|
|
40
43
|
"@langchain/core": "^1.4.0",
|
|
41
44
|
"@langchain/mcp-adapters": "^2.0.3",
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import {MCPAdapter, ToolException} from '@langchain/mcp-adapters'
|
|
2
2
|
import {type AgentMiddleware, createMiddleware, ToolMessage} from 'langchain'
|
|
3
|
+
import {z} from 'zod'
|
|
3
4
|
|
|
5
|
+
import {version} from '../package.json' with {type: 'json'}
|
|
4
6
|
import {connectionError, describeError, httpError} from './describeError'
|
|
5
7
|
import {type SanityContextOptions, validateOptions} from './options'
|
|
6
8
|
|
|
@@ -8,8 +10,9 @@ import {type SanityContextOptions, validateOptions} from './options'
|
|
|
8
10
|
export interface SanityContextLangChain {
|
|
9
11
|
/**
|
|
10
12
|
* Pass to `createAgent({middleware: [...]})` as the first entry, so other middleware sees the
|
|
11
|
-
* Sanity tools.
|
|
12
|
-
*
|
|
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.
|
|
13
16
|
*
|
|
14
17
|
* Errors from the Sanity tools go to the model. Like any middleware that wraps tool calls, it
|
|
15
18
|
* makes LangChain rethrow errors from the agent's own tools; add LangChain's
|
|
@@ -61,14 +64,48 @@ export function createSanityContext(options: SanityContextOptions): SanityContex
|
|
|
61
64
|
clearTimeout(timer)
|
|
62
65
|
}
|
|
63
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
|
+
}
|
|
64
95
|
const warnedCollisions = new Set<string>()
|
|
65
96
|
let shown: Map<string, Awaited<ReturnType<typeof listTools>>[number]> | undefined
|
|
66
97
|
|
|
67
98
|
const middleware = createMiddleware({
|
|
68
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
|
+
}),
|
|
69
105
|
wrapModelCall: async (request, handler) => {
|
|
70
106
|
// LangChain rejects a middleware tool that shares a name with one of the agent's own tools.
|
|
71
107
|
const taken = new Set(request.tools.map((t) => t.name))
|
|
108
|
+
const initialContext = request.state._sanityInitialContext
|
|
72
109
|
const tools = (await listTools()).filter((tool) => {
|
|
73
110
|
if (!taken.has(tool.name)) return true
|
|
74
111
|
if (!warnedCollisions.has(tool.name)) {
|
|
@@ -80,7 +117,13 @@ export function createSanityContext(options: SanityContextOptions): SanityContex
|
|
|
80
117
|
return false
|
|
81
118
|
})
|
|
82
119
|
shown = new Map(tools.map((tool) => [tool.name, tool]))
|
|
83
|
-
return handler({
|
|
120
|
+
return handler({
|
|
121
|
+
...request,
|
|
122
|
+
tools: [...request.tools, ...tools],
|
|
123
|
+
...(initialContext && {
|
|
124
|
+
systemMessage: request.systemMessage.concat(`\n\n${initialContext}`),
|
|
125
|
+
}),
|
|
126
|
+
})
|
|
84
127
|
},
|
|
85
128
|
wrapToolCall: async (request, handler) => {
|
|
86
129
|
// LangChain only knows the agent's own tools, so run the Sanity tool the model was shown. A run
|