Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(gateway): detect client OpenViking tools under any MCP server name (#5930)
t0saki2e706d7193aa
diff --git a/docs/en/guides/15-gateway.md b/docs/en/guides/15-gateway.mdindex 269987002..22f094302 100644--- a/docs/en/guides/15-gateway.md+++ b/docs/en/guides/15-gateway.md@@ -47,7 +47,7 @@ Two terms first. **Recall** means searching OpenViking for memory relevant to a| What you do | What you get | What it costs | What to watch || --- | --- | --- | --- |-| Point the base URL at the gateway and replace the API key with a gateway key. For Claude Code, also set `CLAUDE_CODE_GATEWAY_HINT_HEADERS=1` so sub-agent and background requests are labeled and are not recalled for or saved. | Relevant memory added to every new message, plus your user profile at the start of a conversation; conversations saved to OpenViking and turned into new memories; automatic compaction of long conversations; optionally, a model that searches, reads and writes OpenViking itself (see the [next section](#agentic-memory-for-any-client)). | The first model call of each new message waits up to 2 extra seconds; added memory is billed as input tokens, mostly at the cached rate on later requests; the turn that triggers compaction makes one extra model call. | Added memory is invisible in the client (the provider does see it), and Studio's request log records only counts and timing. Without a configured context window, the gateway assumes 1,000,000 tokens when deciding when to compact; for models with smaller windows, ask an admin to set the real window, or long conversations will be rejected by the provider as too long. When the client has an OpenViking plugin or an MCP server named `openviking`, the gateway does not recall, save or offer OpenViking tools for that conversation. |+| Point the base URL at the gateway and replace the API key with a gateway key. For Claude Code, also set `CLAUDE_CODE_GATEWAY_HINT_HEADERS=1` so sub-agent and background requests are labeled and are not recalled for or saved. | Relevant memory added to every new message, plus your user profile at the start of a conversation; conversations saved to OpenViking and turned into new memories; automatic compaction of long conversations; optionally, a model that searches, reads and writes OpenViking itself (see the [next section](#agentic-memory-for-any-client)). | The first model call of each new message waits up to 2 extra seconds; added memory is billed as input tokens, mostly at the cached rate on later requests; the turn that triggers compaction makes one extra model call. | Added memory is invisible in the client (the provider does see it), and Studio's request log records only counts and timing. Without a configured context window, the gateway assumes 1,000,000 tokens when deciding when to compact; for models with smaller windows, ask an admin to set the real window, or long conversations will be rejected by the provider as too long. When the client has an OpenViking plugin, the gateway does not recall, save or offer OpenViking tools for that conversation; when it only has OpenViking MCP tools, the gateway still recalls and saves but does not offer its own tools. |@@ -141,7 +141,7 @@ The tools come straight from the MCP tool list your OpenViking server provides,- **Read-only tools by default.** New context profiles have **OpenViking tools** on, including those made with **Create with recommended settings**. Only the read-only tools are selected: `find`, `search`, `grep`, `glob`, `list`, `tree`, `read`, `list_watches`, `get_acl`, `list_users`, `list_groups` and `health`. The tools that change data are left unchecked: `remember`, `write`, `edit`, `add_resource`, `add_skill`, `forget`, `set_acl` and `cancel_watch`. To let the model save memories, check `remember`; to let it import web pages or attachments, check `add_resource`. Tools that OpenViking adds later are selected automatically. Existing profiles keep their settings. The full set of tool definitions adds about 3,500 input tokens to every request in the conversation, so unchecking tools nobody needs also saves tokens. Changes apply to new conversations only.- **Limits.** Rounds, **Total time** and the token budget are unlimited by default: the model keeps using OpenViking tools until it finishes. In a streaming request, the user can stop the reply at any time; a non-streaming request keeps running after the client disconnects, so set **Total time** if your clients send non-streaming requests. If you set a round limit or token budget, once it is used up the gateway refuses further OpenViking calls and the model answers with the results it already has; if the model keeps calling after being refused, the request fails. If you set **Total time**, a request that runs longer than that fails. A single call that runs longer than 30 seconds returns an error to the model.-- **Client requirements.** The client must send the full history every turn; with OpenAI Responses it must also set `store: false`. The gateway does not offer OpenViking tools when the client forces a specific tool or asks for structured output, when the upstream has **Allow OpenViking tools** off, or when the upstream is DeepSeek with **Restore reasoning the client drops** off and the request does not turn thinking off. With tools present, DeepSeek requires the reasoning of every earlier reply, which many clients do not send back; DeepSeek upstreams have **Restore reasoning the client drops** on by default, so the gateway puts that reasoning back and tools work with thinking on. See [Upstreams](22-gateway-operations.md#upstreams). Whether a conversation gets tools is decided at its first request.+- **Client requirements.** The client must send the full history every turn; with OpenAI Responses it must also set `store: false`. The gateway does not offer OpenViking tools when the client forces a specific tool or asks for structured output, when the upstream has **Allow OpenViking tools** off, or when the upstream is DeepSeek with **Restore reasoning the client drops** off and the request does not turn thinking off. With tools present, DeepSeek requires the reasoning of every earlier reply, which many clients do not send back; DeepSeek upstreams have **Restore reasoning the client drops** on by default, so the gateway puts that reasoning back and tools work with thinking on. See [Upstreams](22-gateway-operations.md#upstreams). Whether a conversation gets tools is decided at its first request that could use them, and they are turned off if the client turns out to have OpenViking tools of its own.For the full conditions, limit settings, file imports and failure handling, see [OpenViking tools](22-gateway-operations.md#openviking-tools).@@ -186,11 +186,12 @@ Keep the plugin for Claude Code, Codex or pi when you want per-project memory an**Using both.** When a request shows signs of an OpenViking plugin, the gateway stops adding memory, saving turns and offering OpenViking tools for that conversation and only forwards it, so nothing is added or saved twice. It looks for:- memory blocks that plugins insert into the prompt: `<openviking-context>`, `<relevant-memories>`, `<relevant-memory>` or `<memory-context>`;-- a client tool whose name contains an `openviking` segment, such as `openviking_search` or `mcp__openviking__find`, so a client that has the OpenViking MCP server configured under the name `openviking` counts too;- an `X-OpenViking-Plugin` request header, which plugin and app authors can send to opt out explicitly.The decision is permanent for that conversation; start a new conversation without the plugin to use gateway memory again. Other conversations are not affected. On Studio's **Requests** tab these requests are flagged **OpenViking plugin in use**.+OpenViking MCP tools alone, without a plugin, do not count: the gateway keeps adding memory and saving turns, and only stops offering its own OpenViking tools so the model does not see two sets (the `tool_name_collision` reason in [Gateway operations](22-gateway-operations.md)).+## Quick startThis walkthrough runs OpenViking Server, the gateway and a test client on one machine. You need:@@ -355,7 +356,7 @@ export CLAUDE_CODE_GATEWAY_HINT_HEADERS=1- Claude Code sends its own session ID, so conversations are recognized automatically, including after `--resume`.- The upstream must accept the model names Claude Code asks for. Leave the upstream's model list empty, list those names, or map them with model aliases to the model your provider serves.- A Claude subscription login does not work through the gateway; requests with a subscription token are rejected. Configure the upstream with a provider API key.-- If Claude Code also has the OpenViking plugin or the OpenViking MCP server, the gateway steps aside for those conversations (see [Gateway or plugin?](#gateway-or-plugin)).+- If Claude Code also has the OpenViking plugin, the gateway steps aside for those conversations (see [Gateway or plugin?](#gateway-or-plugin)). With only the OpenViking MCP server, the gateway keeps its memory but leaves the OpenViking tools to the MCP server.### Codex CLIdiff --git a/docs/en/guides/22-gateway-operations.md b/docs/en/guides/22-gateway-operations.mdindex 55c592d5e..f99d5371f 100644--- a/docs/en/guides/22-gateway-operations.md+++ b/docs/en/guides/22-gateway-operations.md@@ -504,7 +504,7 @@ New context profiles have **OpenViking tools** on, including those made with **CThe notice names the tool and, where available, what it works on: the search query, the URI read, listed or written, or the file or skill being imported. In a streaming reply it appears as soon as the call starts, so users can see that something is happening during a slow import; a nonstreaming reply gets the same lines in the final message. The outcome is added when the call ends: `done`; `failed` when the call returned an error; `skipped` when the gateway refused the call and did not run it, for example because the round limit or the token budget was reached. Each notice is a paragraph of its own. In Chat Completions the notices are part of the reply text. In Anthropic Messages the notices for one round of calls share one text block, and in Responses they share one assistant message. The model never sees these lines; it gets the actual calls and results. The gateway does not save the notices to OpenViking either. To hide them, turn off **Show tool calls** in the profile's **OpenViking tools** section, and the reply contains only the model's own output. Like the other tool settings, the change applies to new conversations.-Whether a conversation gets tools is decided at its first request and kept, so profile changes reach new conversations only. When a request runs without tools, its detail on the Requests tab says why:+Whether a conversation gets tools is decided at its first request that could use them, not at a helper request such as title generation, and kept, so profile changes reach new conversations only. The one exception turns tools off: when the client shows OpenViking tools of its own before the model has called a gateway tool, for example because an MCP server connected after the first turn. When a request runs without tools, its detail on the Requests tab says why:| Reason | Cause || --- | --- |@@ -515,9 +515,9 @@ Whether a conversation gets tools is decided at its first request and kept, so p| `tools_non_function` | The Chat Completions client sent a tool of a type other than function. || `tools_forced_choice` | `tool_choice` is `required` or names a specific tool. || `deepseek_reasoning_history_required` | The upstream's provider is DeepSeek, the request does not turn thinking off (`"thinking": {"type": "disabled"}`), and earlier replies would reach it without their reasoning: **Restore reasoning the client drops** is off, or this request cannot restore it because the conversation moved upstream, lost its memory record or has thinking resent as text. Standard Responses requests have no `thinking` field, so they count as thinking on. |-| `tool_name_collision` | The client defines a tool with one of the `openviking_*` names. |+| `tool_name_collision` | The client already has OpenViking tools, so the gateway leaves its own out for the rest of the conversation, except on a branch where the model already called them. A misdetection also lasts for the conversation; start a new one. This means: an MCP server name (`server_label`, `mcp_server_name`, `mcp_servers[].name`) contains the word `openviking`; a tool named after an OpenViking tool has that word too, such as `mcp__claude_ai_OpenViking__search` (a connector's `authenticate` tool does not count), including deferred tools listed by name on their own line; or a prefixed tool named after an OpenViking tool, such as `mcp__ov__read`, mentions `viking://`. On any request, a client tool with the same name as a gateway tool also counts, since upstreams reject duplicate names. || `tools_unavailable` | OpenViking could not provide its tool list and no previously loaded list was available. Start a new conversation after connectivity recovers. |-| `tools_not_selected_at_session_start` | The profile has tools on, but the conversation's first request could not use them (for one of the reasons above), so the conversation has none. |+| `tools_not_selected_at_session_start` | The profile has tools on, but the conversation's tool list is empty: the profile selects no OpenViking tools, or the conversation started before an upgrade that left it without tools. Start a new conversation. |Housekeeping and sub-agent requests, and conversations where an OpenViking plugin was detected, do not get OpenViking tools. When such a request resends history in which the model used them, the gateway still sends the tool definitions so that the history stays valid, but refuses new OpenViking calls. The client's own tools stay available in every request.@@ -798,9 +798,9 @@ Studio calls the management API on OpenViking Server under `/api/v1/admin/gatewa| Symptom | Cause | What to do || --- | --- | --- |-| A conversation gets no recall and is not saved | An OpenViking plugin or an MCP server named `openviking` was detected, and the gateway stepped aside, leaving recall, saving and OpenViking tools to the plugin. | Expected: it keeps the same content from being added or saved twice. See [Gateway or plugin?](15-gateway.md#gateway-or-plugin). |+| A conversation gets no recall and is not saved | An OpenViking plugin was detected, and the gateway stepped aside, leaving recall, saving and OpenViking tools to the plugin. | Expected: it keeps the same content from being added or saved twice. See [Gateway or plugin?](15-gateway.md#gateway-or-plugin). || Saving shows **Retrying**, then **Paused** | OpenViking rejected the save or could not be reached, often because the user's OpenViking key was regenerated. | The gateway recovers on its own once the cause is fixed; if the key is no longer valid, issue a new gateway key. See [Conversations do not appear in OpenViking](#conversations-do-not-appear-in-openviking). |-| The profile has tools on, but the conversation has none | The conversation's first request did not meet the tool conditions, or the client does not send the full history. | Check the reason in the request log (see [OpenViking tools](#openviking-tools)), fix it and start a new conversation. |+| The profile has tools on, but the conversation has none | No request that could use tools has arrived yet, OpenViking's tool list failed to load for the first one, the client does not send the full history, or the client has OpenViking tools of its own. | Check the reason in the request log (see [OpenViking tools](#openviking-tools)). `tool_name_collision` is expected when the client has the OpenViking MCP server; for other reasons, fix the cause and start a new conversation. || Requests go without memory | OpenViking unreachable or too slow, budget used up, nothing relevant, and so on. | See [No memory is added](#no-memory-is-added). || The provider rejects a long conversation as too long | The gateway does not know the model's real window and compacts too late. | See [Long conversations hit the context limit](#long-conversations-hit-the-context-limit). |diff --git a/docs/zh/guides/15-gateway.md b/docs/zh/guides/15-gateway.mdindex 35e65e057..446335275 100644--- a/docs/zh/guides/15-gateway.md+++ b/docs/zh/guides/15-gateway.md@@ -47,7 +47,7 @@ description: 把任何使用 API Key 的模型客户端指向 OpenViking 网关| 你要做的 | 你会得到 | 额外开销 | 需要留意 || --- | --- | --- | --- |-| 把 Base URL 改成网关地址,API Key 换成网关密钥。Claude Code 还要设置 `CLAUDE_CODE_GATEWAY_HINT_HEADERS=1`,给子 Agent 和后台请求加上标记,避免为它们召回和保存。 | 每条新消息都补充相关记忆,对话开头还提供用户画像;对话保存回 OpenViking 并提取成新记忆;长对话自动压缩;可选:模型主动检索、读取和写入 OpenViking(见[下一节](#让任意客户端拥有-agentic-记忆))。 | 每条新消息的第一次模型调用最多多等 2 秒;补充的记忆按输入 token 计费,之后的请求里大部分按缓存价计费;触发压缩的那一轮多一次模型调用。 | 补充的记忆在客户端里看不到(服务商看得到),Studio 的请求日志也只记条数和耗时;没有设置上下文窗口时,网关按 1,000,000 token 的窗口决定何时压缩,使用窗口更小的模型时要请管理员填上实际窗口,否则长对话会因过长被服务商拒绝;客户端装了 OpenViking 插件或名为 `openviking` 的 MCP 服务器时,网关不为这段对话召回、保存,也不提供 OpenViking 工具。 |+| 把 Base URL 改成网关地址,API Key 换成网关密钥。Claude Code 还要设置 `CLAUDE_CODE_GATEWAY_HINT_HEADERS=1`,给子 Agent 和后台请求加上标记,避免为它们召回和保存。 | 每条新消息都补充相关记忆,对话开头还提供用户画像;对话保存回 OpenViking 并提取成新记忆;长对话自动压缩;可选:模型主动检索、读取和写入 OpenViking(见[下一节](#让任意客户端拥有-agentic-记忆))。 | 每条新消息的第一次模型调用最多多等 2 秒;补充的记忆按输入 token 计费,之后的请求里大部分按缓存价计费;触发压缩的那一轮多一次模型调用。 | 补充的记忆在客户端里看不到(服务商看得到),Studio 的请求日志也只记条数和耗时;没有设置上下文窗口时,网关按 1,000,000 token 的窗口决定何时压缩,使用窗口更小的模型时要请管理员填上实际窗口,否则长对话会因过长被服务商拒绝;客户端装了 OpenViking 插件时,网关不为这段对话召回、保存,也不提供 OpenViking 工具;只接了 OpenViking MCP 工具时,网关照常召回和保存,但不再提供自己的工具。 |@@ -141,7 +141,7 @@ Relevant memory from OpenViking. Use the openviking_read tool to expand URIs.- **默认只提供只读工具。** 新建的上下文配置默认打开 **OpenViking 工具**,“使用推荐设置创建”也一样。默认勾选的是只读工具:`find`、`search`、`grep`、`glob`、`list`、`tree`、`read`、`list_watches`、`get_acl`、`list_users`、`list_groups` 和 `health`。会修改数据的工具默认不勾选:`remember`、`write`、`edit`、`add_resource`、`add_skill`、`forget`、`set_acl` 和 `cancel_watch`。想让模型保存记忆,就勾选 `remember`;想让它导入网页或附件,就勾选 `add_resource`。OpenViking 以后新增的工具会自动勾选。已有的上下文配置保留原来的设置。全部工具定义约占 3,500 个输入 token,会随对话中的每个请求发送,所以取消用不到的工具也能节省 token。改动只影响新对话。- **上限。** 工具轮数、**总时长**和 **Token 预算**默认都不限:模型会一直使用 OpenViking 工具直到完成。流式请求中,用户可以随时中断回复;非流式请求在客户端断开后仍会继续执行,如果客户端发送非流式请求,建议设置**总时长**。设置了工具轮数或 Token 预算的,用完后网关拒绝之后的 OpenViking 调用,模型用已有结果继续回答;模型被拒后仍坚持调用,这个请求就会报错。设置了**总时长**的,请求超过这个时长就会失败。单次调用超过 30 秒,这次调用向模型返回错误。-- **客户端要求。** 客户端要每轮回传完整历史;使用 OpenAI Responses 时要设置 `store: false`。客户端强制指定某个工具或要求结构化输出、上游关闭了**允许 OpenViking 工具**,或者上游是 DeepSeek、关闭了**补全推理内容回传**而请求又没有关闭思考模式时,网关不提供 OpenViking 工具。DeepSeek 要求带工具的请求回传之前每条回复的推理内容,而很多客户端不会发回来;DeepSeek 上游默认开启**补全推理内容回传**,由网关补回这部分内容,所以保持思考模式也能使用工具,见[上游](22-gateway-operations.md#上游)。对话是否带工具,在它的第一个请求时就决定了。+- **客户端要求。** 客户端要每轮回传完整历史;使用 OpenAI Responses 时要设置 `store: false`。客户端强制指定某个工具或要求结构化输出、上游关闭了**允许 OpenViking 工具**,或者上游是 DeepSeek、关闭了**补全推理内容回传**而请求又没有关闭思考模式时,网关不提供 OpenViking 工具。DeepSeek 要求带工具的请求回传之前每条回复的推理内容,而很多客户端不会发回来;DeepSeek 上游默认开启**补全推理内容回传**,由网关补回这部分内容,所以保持思考模式也能使用工具,见[上游](22-gateway-operations.md#上游)。对话是否带工具,由它第一个能用工具的请求决定;如果客户端自己也接了 OpenViking 工具,网关会关掉自己的工具。完整的条件、上限设置、文件导入方式和失败处理,见[OpenViking 工具](22-gateway-operations.md#openviking-工具)。@@ -183,14 +183,15 @@ OpenViking 也可以通过运行在 Agent 内部的插件接入 Claude Code、CoClaude Code、Codex 和 pi 如果需要按项目区分记忆,或者要求每次工具调用都能看到并确认,就继续用插件。没有插件的客户端,以及想集中管理服务商、密钥和记忆设置的场景,用网关。-**两者同时使用。** 请求中出现 OpenViking 插件的迹象时,网关会停止为这段对话补充记忆、保存对话和提供 OpenViking 工具,只负责转发,这样同一份内容不会被补充两次或保存两次。网关根据以下三类迹象判断:+**两者同时使用。** 请求中出现 OpenViking 插件的迹象时,网关会停止为这段对话补充记忆、保存对话和提供 OpenViking 工具,只负责转发,这样同一份内容不会被补充两次或保存两次。网关根据以下两类迹象判断:- 插件插入提示词的记忆块:`<openviking-context>`、`<relevant-memories>`、`<relevant-memory>` 或 `<memory-context>`;-- 名称中带 `openviking` 段的客户端工具,例如 `openviking_search` 或 `mcp__openviking__find`,所以把 OpenViking MCP 服务器配置成 `openviking` 这个名字的客户端也算在内;- `X-OpenViking-Plugin` 请求头,插件和应用的作者可以发送它,明确表示不需要网关补充记忆。这个判断对这段对话一直有效;想重新用上网关记忆,需要在不带插件的情况下开始新对话。其他对话不受影响。在 Studio 的“请求日志”标签页里,这些请求会标上**检测到 OpenViking 插件**。+只接了 OpenViking MCP 工具、没有装插件的客户端不算:网关照常补充记忆和保存对话,只是不再提供自己的 OpenViking 工具,免得模型看到两套(即[网关运维](22-gateway-operations.md)里的 `tool_name_collision`)。+## 快速开始下面的流程在一台机器上运行 OpenViking Server、网关和测试客户端。你需要:@@ -355,7 +356,7 @@ export CLAUDE_CODE_GATEWAY_HINT_HEADERS=1- Claude Code 会发送自己的会话 ID,所以网关能自动识别对话,`--resume` 之后也一样。- 上游必须接受 Claude Code 请求的模型名。可以把上游的模型列表留空、列出这些名称,或者用模型别名把它们映射到服务商提供的模型。- Claude 订阅登录无法通过网关使用,携带订阅令牌的请求会被拒绝。请为上游配置服务商的 API Key。-- 如果 Claude Code 同时装了 OpenViking 插件或 OpenViking MCP 服务器,网关会让出这些对话(见[网关还是插件](#网关还是插件))。+- 如果 Claude Code 同时装了 OpenViking 插件,网关会让出这些对话(见[网关还是插件](#网关还是插件))。只接了 OpenViking MCP 服务器时,网关照常补充记忆,OpenViking 工具交给 MCP 服务器。### Codex CLIdiff --git a/docs/zh/guides/22-gateway-operations.md b/docs/zh/guides/22-gateway-operations.mdindex 1081c222b..9947469b0 100644--- a/docs/zh/guides/22-gateway-operations.md+++ b/docs/zh/guides/22-gateway-operations.md@@ -504,7 +504,7 @@ server {提示写明工具名;能够识别调用对象时,还会显示:检索的查询词,读取、列出或写入的 URI,或者正在导入的文件或技能。流式回复中,调用一开始提示就会出现,所以导入这类耗时的调用进行时,用户也能看到网关在工作;非流式回复会在最终消息里带上同样的提示。调用结束后再补上结果:`done` 表示完成,`failed` 表示调用返回了错误,`skipped` 表示网关拒绝了这次调用,没有执行,例如工具轮数已达上限或 token 预算已经用完。每条提示单独成段。在 Chat Completions 中,提示是回复文本的一部分;在 Anthropic Messages 中,同一轮调用的提示放在同一个文本块里;在 Responses 中,同一轮调用的提示放在同一条助手消息里。模型看不到这些提示,它收到的是真实的调用和结果;网关也不会把提示保存到 OpenViking。要隐藏提示,在上下文配置的 **OpenViking 工具**部分关闭**显示工具调用**,回复里就只有模型自己的输出。和其他工具设置一样,改动只影响新对话。-对话是否带工具,在它的第一个请求时就决定了,之后保持不变,所以修改上下文配置只影响新对话。请求没有带工具时,请求日志的详情会说明原因:+对话是否带工具,由它第一个能用工具的请求决定(生成标题这类辅助请求不算),之后保持不变,所以修改上下文配置只影响新对话。唯一的例外是关闭工具:模型还没调用过网关工具时,客户端出现了自己的 OpenViking 工具,例如 MCP 服务器在第一轮之后才连上。请求没有带工具时,请求日志的详情会说明原因:| 原因 | 说明 || --- | --- |@@ -515,9 +515,9 @@ server {| `tools_non_function` | Chat Completions 客户端传入了 function 以外类型的工具。 || `tools_forced_choice` | `tool_choice` 为 `required`,或者指定了某个工具。 || `deepseek_reasoning_history_required` | 上游的服务商是 DeepSeek,请求没有关闭思考模式(`"thinking": {"type": "disabled"}`),而之前的回复发到上游时会缺少推理内容:关闭了**补全推理内容回传**,或者这个请求补不回推理内容,因为对话换了上游、丢了记忆记录,或者思考内容被当作正文发回。标准的 Responses 请求没有 `thinking` 字段,按开启思考模式处理。 |-| `tool_name_collision` | 客户端定义了与某个 `openviking_*` 工具同名的工具。 |+| `tool_name_collision` | 客户端已接入 OpenViking 工具,网关在这段对话剩下的部分不再提供自己的工具;模型已经调用过网关工具的分支除外。误判同样会持续整段对话,开新对话即可。满足以下任一条件即算:MCP 服务名(`server_label`、`mcp_server_name`、`mcp_servers[].name`)含有单词 `openviking`;以 OpenViking 工具名命名的工具名中也含这个单词,如 `mcp__claude_ai_OpenViking__search`(连接器的 `authenticate` 工具不算),包括独占一行列出的延迟加载工具名;带前缀、以 OpenViking 工具名结尾的工具(如 `mcp__ov__read`)在定义中出现 `viking://`。此外,任一请求中客户端工具与网关工具同名也算,因为上游会拒绝重名工具。 || `tools_unavailable` | 无法从 OpenViking 加载工具清单,也没有之前加载成功的清单。连接恢复后请开始新对话。 |-| `tools_not_selected_at_session_start` | 上下文配置开启了工具,但对话的第一个请求因为上面某个原因用不了工具,所以整段对话都没有工具。 |+| `tools_not_selected_at_session_start` | 上下文配置开启了工具,但这段对话的工具列表是空的:配置里没有选中任何 OpenViking 工具,或者对话是在网关升级前开始的、当时没拿到工具。开始新对话即可。 |辅助请求、子 Agent 请求和检测到 OpenViking 插件的对话都不带 OpenViking 工具。这类请求如果回传了模型用过这些工具的历史,网关仍会附上工具定义,让这段历史保持有效,但会拒绝新的 OpenViking 调用。客户端自己的工具在每个请求里都照常可用。@@ -798,9 +798,9 @@ Studio 通过 OpenViking Server 上 `/api/v1/admin/gateway/` 下的管理 API| 现象 | 原因 | 处理 || --- | --- | --- |-| 某段对话没有召回,也没有保存 | 检测到 OpenViking 插件或名为 `openviking` 的 MCP 服务器,网关让出了这段对话,召回、保存和 OpenViking 工具都交给插件。 | 正常行为,避免同一份内容补充两次、保存两次,见[网关还是插件](15-gateway.md#网关还是插件)。 |+| 某段对话没有召回,也没有保存 | 检测到 OpenViking 插件,网关让出了这段对话,召回、保存和 OpenViking 工具都交给插件。 | 正常行为,避免同一份内容补充两次、保存两次,见[网关还是插件](15-gateway.md#网关还是插件)。 || 保存显示“重试中”,之后变成“已暂停” | OpenViking 拒绝保存或无法访问,常见原因是用户的 OpenViking 密钥被重新生成过。 | 修好原因后网关会自动恢复;密钥失效时重新签发网关密钥,见[OpenViking 中看不到对话](#openviking-中看不到对话)。 |-| 上下文配置开启了工具,对话里却没有 | 对话的第一个请求不满足工具条件,或者客户端没有回传完整历史。 | 在请求日志里查看停用原因(见 [OpenViking 工具](#openviking-工具)),修正后开始新对话。 |+| 上下文配置开启了工具,对话里却没有 | 还没有能用工具的请求、第一个能用的请求加载 OpenViking 工具列表失败、客户端没有回传完整历史,或者客户端自己接了 OpenViking 工具。 | 在请求日志里查看停用原因(见 [OpenViking 工具](#openviking-工具))。客户端接了 OpenViking MCP 服务器时出现 `tool_name_collision` 属于正常;其他原因修正后开始新对话。 || 请求不带记忆 | OpenViking 无法访问或超时、预算用完、没有相关内容等。 | 见[没有补充记忆](#没有补充记忆)。 || 长对话被服务商以过长为由拒绝 | 网关不知道模型的实际窗口,压缩得太晚。 | 见[长对话超出上下文长度](#长对话超出上下文长度)。 |diff --git a/openviking_gateway/kernel.py b/openviking_gateway/kernel.pyindex 4f8afe242..88fef8619 100644--- a/openviking_gateway/kernel.py+++ b/openviking_gateway/kernel.py@@ -32,6 +32,7 @@ from .profile import build_profilefrom .protocols import (classify,clean_text,+ client_openviking_tools,is_user,plugin_present,prefix_chain,@@ -46,7 +47,7 @@ from .state_store import get_statefrom .storage import KernelStore, digestfrom .tool_catalog import reply_block_reason, select_tools, tool_block_reasonfrom .tool_protocols import hidden_chain, replay_hidden, tool_protocol-from .tool_protocols.common import SummaryError+from .tool_protocols.common import PREFIX, SummaryErrorfrom .vendors import parameter_fingerprintfrom .windows import remind, status_line@@ -209,9 +210,7 @@ class MemoryKernel:scope, sid, list(dict.fromkeys(["", *chain, *body_chain])), ancestors)plugin = plugin_present(body, headers)- root = await self.session_root(- records, scope, sid, body, protocol, upstream, policy, credential, plugin- )+ root = await self.session_root(records, scope, sid, body, upstream, policy, credential)upstream = next((u for u in upstreams if u["id"] == root["upstream_id"]), upstream)policy = Policy.model_validate(root["policy"])kind, anchor = classify(body, headers, messages)@@ -221,6 +220,19 @@ class MemoryKernel:disabled = True# A token count gets gateway tools exactly when the request it measures would.owner = not disabled and kind in {"user", "continuation"}+ root = await self.session_tools(+ records,+ scope,+ sid,+ root,+ body,+ protocol,+ upstream,+ credential,+ owner,+ body_chain,+ counting,+ )kind = "count" if counting else kindresult = {**body, adapter.field: [dict(m) for m in sent]}prepared = Prepared(@@ -296,23 +308,9 @@ class MemoryKernel:result["input"] = body["input"]return prepared- async def session_root(- self, records, scope, sid, body, protocol, upstream, policy, credential, plugin- ):+ async def session_root(self, records, scope, sid, body, upstream, policy, credential):root = records.get((K.ROOT, ""))if root is None:- # The tool list is frozen here, so a failed load leaves the session without tools.- tools, reason = [], ""- if (- not plugin- and policy.get("gateway_tools")- and not tool_block_reason(body, protocol, upstream)- ):- try:- catalog = await self.viking.tools(credential["openviking_key"])- tools = select_tools(catalog, policy)- except VikingError:- reason = "tools_unavailable"root = await self.store.replay.put(scope,sid,@@ -320,8 +318,6 @@ class MemoryKernel:"",{"upstream_id": upstream["id"],- "tools": tools,- "tool_skip_reason": reason,"policy": policy,"credential_id": credential["id"],"vendor": {@@ -333,6 +329,60 @@ class MemoryKernel:)return root+ async def session_tools(+ self,+ records,+ scope,+ sid,+ root,+ body,+ protocol,+ upstream,+ credential,+ owner,+ body_chain,+ counting=False,+ ):+ """The root with the session's gateway tools and why there are none."""+ policy = root["policy"]+ # A branch where the model called a gateway tool keeps the tools, so its+ # history still replays.+ used = any((K.HIDDEN, anchor) in records for anchor in body_chain)+ # Sessions created before tools had their own record keep them in the root.+ decision = records.get((K.TOOLS, "")) or (root if "tools" in root else None)+ if decision is None:+ # Helper requests, such as a title with structured output, often come first;+ # the first request that could use tools decides for the session. So does+ # one resending tool rounds, as a sub-agent in a session of its own does.+ if not (owner or used) or not policy.get("gateway_tools"):+ return {**root, "tools": [], "tool_skip_reason": ""}+ if tool_block_reason(body, protocol, upstream):+ return {**root, "tools": [], "tool_skip_reason": ""}+ # A failed load leaves the session without tools.+ tools, reason = [], ""+ try:+ tools = select_tools(await self.viking.tools(credential["openviking_key"]), policy)+ except VikingError:+ reason = "tools_unavailable"+ decision = await self.store.replay.put(+ scope, sid, K.TOOLS, "", {"tools": tools, "tool_skip_reason": reason}+ )+ tools, reason = decision["tools"], decision.get("tool_skip_reason", "")+ closed = records.get((K.TOOLS_CLOSED, ""))+ # Client OpenViking tools may appear late, as when MCP servers connect after the+ # first turn. Until the model has called a gateway tool, they turn gateway tools+ # off for good; the client changed its tool list then, so caches miss anyway.+ # A token count may cover only part of the client's tools, so it never decides.+ if tools and closed is None and owner and not counting and not used:+ names = [t["function"]["name"].removeprefix(PREFIX) for t in tools]+ if client_openviking_tools(body, names):+ closed = await self.store.replay.put(+ scope, sid, K.TOOLS_CLOSED, "", {"reason": "tool_name_collision"}+ )+ if closed is not None and not used:+ tools, reason = [], closed["reason"]+ return {**root, "tools": tools, "tool_skip_reason": reason}+@staticmethoddef configure_tools(request, policy, owner):tools = request.root["tools"]@@ -346,9 +396,13 @@ class MemoryKernel:reason = tool_block_reason(request.original, request.protocol, request.upstream, restores)+ # Upstreams reject duplicate tool names, so an exact clash always skips.names = {t["function"]["name"] for t in tools}collision = any(- t.get("function", t).get("name") in names for t in request.original.get("tools", [])+ isinstance(t, dict)+ and isinstance(t.get("function", t), dict)+ and t.get("function", t).get("name") in names+ for t in request.original.get("tools") or [])hidden = any((K.HIDDEN, anchor) in request.records for anchor in request.body_chain)if reason or collision:@@ -363,7 +417,7 @@ class MemoryKernel:request.metrics["tools_tokens"] = token_estimate(orjson.dumps(adapter.wire_tools(tools)).decode())- elif policy.gateway_tools:+ elif policy.gateway_tools and owner:request.metrics["tool_skip_reason"] = (tool_block_reason(request.original, request.protocol, request.upstream)or request.root["tool_skip_reason"]diff --git a/openviking_gateway/protocols.py b/openviking_gateway/protocols.pyindex faa867456..e88fdd46d 100644--- a/openviking_gateway/protocols.py+++ b/openviking_gateway/protocols.py@@ -163,6 +163,22 @@ def prefix_chain(messages: list[dict]) -> list[str]:return result+def client_texts(body: dict) -> list[str]:+ """The system prompt and the client-written messages, without replies or tool output."""+ texts = [text_content({"content": body.get("system", "")}), body.get("instructions", "")]+ for field in ("messages", "input"):+ messages = body.get(field, [])+ if isinstance(messages, str):+ texts.append(messages)+ elif isinstance(messages, list):+ texts.extend(+ text_content(m)+ for m in messages+ if isinstance(m, dict) and m.get("role") in {"user", "system", "developer"}+ )+ return [text for text in texts if isinstance(text, str)]++def plugin_present(body: dict, headers: dict) -> bool:if headers.get("x-openviking-plugin"):return True@@ -184,29 +200,72 @@ def plugin_present(body: dict, headers: dict) -> bool:)return any(re.search(rf"<{re.escape(tag)}(?:\s|>)", text, re.I) for tag in PLUGIN_TAGS)- texts = [text_content({"content": body.get("system", "")}), body.get("instructions", "")]- for field in ("messages", "input"):- messages = body.get(field, [])- if isinstance(messages, str):- texts.append(messages)- elif isinstance(messages, list):- texts.extend(- text_content(m)- for m in messages- if isinstance(m, dict) and m.get("role") in {"user", "system", "developer"}- )- if any(marked(text) for text in texts if isinstance(text, str)):- return True- # Only tool definitions identify plugin ownership. File names, tool results- # and assistant prose must never permanently disable a session.- for tool in [*body.get("tools", []), *body.get("additional_tools", [])]:+ # Plugins mark the context they inject. OpenViking tools alone, as from an MCP+ # connection, only keep the gateway's tools out (see client_openviking_tools).+ return any(marked(text) for text in client_texts(body))+++OPENVIKING_WORD = r"(?<![a-z0-9])openviking(?![a-z0-9])"+++def client_openviking_tools(body: dict, names) -> bool:+ """Whether the client already exposes OpenViking tools, whatever its MCP server is named.++ ``names`` are the bare OpenViking tool names, such as ``read`` and ``add_resource``.+ """+ if not names:+ return False+ pending = []+ for key in ("tools", "additional_tools", "mcp_servers"):+ if isinstance(body.get(key), list):+ pending.extend(("", tool) for tool in body[key])+ if isinstance(body.get("input"), list):+ for item in body["input"]:+ if isinstance(item, dict) and item.get("type") == "additional_tools":+ if isinstance(item.get("tools"), list):+ pending.extend(("", tool) for tool in item["tools"])+ # Prefixed like mcp__ov__read or ov_read; a bare Read is a client's own tool.+ alternatives = "|".join(map(re.escape, names))+ ending = re.compile(rf"[^a-z0-9](?:{alternatives})$", re.I)+ while pending:+ parent, tool = pending.pop()if not isinstance(tool, dict):continuedefinition = tool.get("function", tool)- name = definition.get("name", definition.get("namespace", ""))- if isinstance(name, str) and re.search(r"(^|__)openviking(?:_|__|$)", name, re.I):+ if not isinstance(definition, dict):+ continue+ labels = [+ parent + definition[key]+ for key in ("name", "namespace", "server_label", "mcp_server_name")+ if isinstance(definition.get(key), str)+ ]+ if isinstance(definition.get("tools"), list):+ # A namespace's tools are named without it, as in mcp__kb + glob; they+ # decide, not the namespace name.+ prefix = (labels[0] + "__") if labels else ""+ pending.extend((prefix, child) for child in definition["tools"])+ continue+ # Hosted MCP servers (Responses mcp, Anthropic mcp_servers and mcp_toolset) list+ # no tools, so their name is all there is.+ server = definition.get("type") in {"mcp", "mcp_toolset", "url"}+ named_tool = isinstance(definition.get("name"), str) and not server+ # A tool must be one of OpenViking's, so a connector's authenticate tool is not.+ if any(+ re.search(OPENVIKING_WORD, label, re.I) and (not named_tool or ending.search(label))+ for label in labels+ ):+ return True+ # A renamed server's tools keep their names and mention viking:// URIs, while+ # a container such as a skill list may quote an OpenViking description too.+ if (+ any(ending.search(label) for label in labels)+ and "viking://" in orjson.dumps(definition).decode().lower()+ ):return True- return False+ # Deferred MCP tools, as in Claude Code's tool search, are listed only by name, one+ # per line; a name mentioned in prose is not a tool.+ deferred = rf"^[ \t]*mcp__[\w-]*?{OPENVIKING_WORD}[\w-]*__(?:{alternatives})[ \t]*$"+ return any(re.search(deferred, text, re.I | re.M) for text in client_texts(body))def is_user(message):diff --git a/openviking_gateway/records.py b/openviking_gateway/records.pyindex cf236adc7..dc5a984c5 100644--- a/openviking_gateway/records.py+++ b/openviking_gateway/records.py@@ -9,6 +9,9 @@ class RecordKind(str, Enum):ROOT = "root"INJECTION = "injection"DISABLED = "disabled"+ # The gateway tools frozen for the session, and the one-way switch that turns them off.+ TOOLS = "tools"+ TOOLS_CLOSED = "tools_closed"HIDDEN = "hidden"REPLACEMENT = "replacement"# The session whose model produced the reply ending at the anchor.diff --git a/tests/gateway/test_kernel.py b/tests/gateway/test_kernel.pyindex 2481abf84..c0d5e7274 100644--- a/tests/gateway/test_kernel.py+++ b/tests/gateway/test_kernel.py@@ -14,6 +14,7 @@ from openviking_gateway.kernel import token_estimatefrom openviking_gateway.models import Policyfrom openviking_gateway.protocols import (classify,+ client_openviking_tools,normalize,parse_body,plugin_present,@@ -416,11 +417,11 @@ async def test_plugin_stop_is_sticky_but_replays_existing_prefix(setup_kernel, c{"role": "assistant", "content": "Answer"},{"role": "user", "content": "Next question"},]- two_body["tools"] = [{"type": "namespace", "name": "mcp__openviking", "tools": []}]+ two_body["system"] = "<openviking-context>Memory</openviking-context>"two = await prepare(kernel, two_body, credential, policy)assert two.disabledassert two.body["messages"][0] == one.body["messages"][0]- del two_body["tools"]+ del two_body["system"]three = await prepare(kernel, two_body, credential, policy)assert three.disabled and len(viking.recalls) == 1@@ -552,14 +553,86 @@ def test_classification_and_plugin_namespaces():== "auxiliary")assert classify({}, {"x-claude-code-agent-id": "child"}, [user])[0] == "subagent"- assert plugin_present(- {- "additional_tools": [- {"namespace": "mcp__openviking_memory", "tools": [{"name": "read"}]}- ]- },- {},+ # OpenViking tools alone, as from an MCP connection, are not a plugin.+ namespaces = {+ "additional_tools": [{"namespace": "mcp__openviking_memory", "tools": [{"name": "read"}]}]+ }+ assert not plugin_present(namespaces, {})+ assert client_openviking_tools(namespaces, OV_NAMES)+++OV_NAMES = ["read", "ls", "glob", "find", "search", "add_resource"]+++ "tools, detected",+ [+ ([{"name": "openviking_search"}], True),+ ([{"name": "mcp__claude_ai_OpenViking__search"}], True),+ ([{"name": "mcp__plugin_openviking-memory_openviking__find"}], True),+ (+ [+ {+ "type": "function",+ "function": {"name": "mcp__ov__read", "description": "Read viking://a"},+ }+ ],+ True,+ ),+ (+ [{"name": "ov_ls", "input_schema": {"properties": {"uri": {"default": "viking://"}}}}],+ True,+ ),+ (+ [{"namespace": "mcp__kb", "tools": [{"name": "glob", "description": "VIKING://user"}]}],+ True,+ ),+ ([{"type": "mcp", "server_label": "OpenViking", "server_url": "https://x/mcp"}], True),+ ([{"type": "mcp_toolset", "mcp_server_name": "openviking"}], True),+ ([{"name": "Read", "description": "Read a local file"}, {"name": "WebSearch"}], False),+ ([{"name": "openvikingish_search"}, {"name": "mcp__myopenviking__find"}], False),+ # A namespace counts by its tools, not its name.+ ([{"namespace": "mcp__openviking_docs", "tools": [{"name": "fetch_page"}]}], False),+ # An unauthenticated claude.ai connector offers only its sign-in tools.+ ([{"name": "mcp__claude_ai_OpenViking__authenticate"}], False),+ # A skill list quoting an OpenViking skill is not an OpenViking tool.+ (+ [+ {+ "name": "skill",+ "description": "<available_skills>viking://resources/</available_skills>",+ }+ ],+ False,+ ),+ ([{"name": "mcp__kb__fetch", "description": "Fetch viking://a"}], False),+ ([{"name": "Read", "description": "Read a file or viking:// URI"}], False),+ ],+)+def test_client_openviking_tools(tools, detected):+ assert client_openviking_tools({"tools": tools}, OV_NAMES) == detected+ assert client_openviking_tools({"additional_tools": tools}, OV_NAMES) == detected+ item = {"type": "additional_tools", "tools": tools}+ assert client_openviking_tools({"input": [item]}, OV_NAMES) == detected+++def test_client_openviking_tools_outside_tool_list():+ servers = {"mcp_servers": [{"type": "url", "url": "https://x/mcp", "name": "openviking"}]}+ assert client_openviking_tools(servers, OV_NAMES)+ deferred = (+ "<system-reminder>Deferred tools:\nmcp__claude_ai_OpenViking__search\n</system-reminder>"+ )+ assert client_openviking_tools({"messages": [{"role": "user", "content": deferred}]}, OV_NAMES)+ signin = "mcp__claude_ai_OpenViking__authenticate\nmcp__claude_ai_OpenViking__complete_authentication"+ assert not client_openviking_tools(+ {"messages": [{"role": "user", "content": signin}]}, OV_NAMES)+ prose = "Why does mcp__openviking__search fail?"+ assert not client_openviking_tools({"messages": [{"role": "user", "content": prose}]}, OV_NAMES)+ reply = {"role": "assistant", "content": "mcp__openviking__search"}+ assert not client_openviking_tools({"messages": [reply]}, OV_NAMES)+ assert not client_openviking_tools({"tools": [{"name": "Read"}]}, [])+ assert not client_openviking_tools({"tools": None, "mcp_servers": None}, OV_NAMES)def test_capture_pairs_tools_and_strips_noise():diff --git a/tests/gateway/test_native_tools.py b/tests/gateway/test_native_tools.pyindex fe01647d3..106f58305 100644--- a/tests/gateway/test_native_tools.py+++ b/tests/gateway/test_native_tools.py@@ -540,9 +540,10 @@ async def test_native_budget_keeps_client_tools_and_output_limit(assert logs[0]["tool_stop_reason"] == "token_budget"[email protected]("own_session", [False, True])@pytest.mark.parametrize("protocol", ["responses", "anthropic"])async def test_subagent_resending_tool_history_replays_it_but_cannot_call(- running_gateway, protocol+ running_gateway, protocol, own_session):app, client, admin, key, _, _ = running_gatewayawait enable_tools(client, admin)@@ -572,10 +573,12 @@ async def test_subagent_resending_tool_history_replays_it_but_cannot_call(else [{"role": "assistant", "content": visible["content"]}])body[field].append({"role": "user", "content": "Explore"})- # A forked sub-agent resends the main history, including the hidden tool round.- response = await client.post(- PATHS[protocol], headers={**headers, "X-Claude-Code-Agent-Id": "child"}, json=body- )+ # A forked sub-agent resends the main history, including the hidden tool round,+ # possibly under a session of its own that never had a request owning tools.+ child = {**headers, "X-Claude-Code-Agent-Id": "child"}+ if own_session:+ child.update({"X-OpenViking-Session": "child-thread", "X-Codex-Parent-Thread-Id": "fork"})+ response = await client.post(PATHS[protocol], headers=child, json=body)assert response.status_code == 200, response.textreplay = requests[2]assert replay["tools"] == requests[0]["tools"]@@ -1065,6 +1068,122 @@ async def test_anthropic_blocked_tools_preserve_client_thinking(assert result.metrics.get("degradation") != "hidden_tool_history_unavailable"+def test_exact_tool_name_clash_skips_replayed_gateway_tools():+ from types import SimpleNamespace++ from openviking_gateway.kernel import MemoryKernel+ from openviking_gateway.models import Policy+ from openviking_gateway.records import RecordKind as K++ tool = {"type": "function", "function": {"name": "openviking_search", "parameters": {}}}+ body = {"model": "m", "messages": [], "tools": [{"name": "openviking_search"}]}+ request = SimpleNamespace(+ root={"tools": [tool]},+ metrics={},+ protocol="anthropic",+ disabled=True,+ strip_replayed_thinking=False,+ thinking_as_text=False,+ original=body,+ body=copy.deepcopy(body),+ upstream={},+ records={(K.HIDDEN, "a"): {}},+ body_chain=["a"],+ tools_active=False,+ hidden_history_unavailable=False,+ )+ MemoryKernel.configure_tools(request, Policy(), owner=False)+ assert request.metrics["tool_skip_reason"] == "tool_name_collision"+ assert request.body["tools"] == body["tools"]+++async def test_title_request_first_does_not_decide_tools(setup_kernel, credential, policy):+ kernel, _, _, _ = setup_kernel+ policy.update(gateway_tools=True, recall=False, capture=False)+ header, upstream = {"x-openviking-session": "title-first"}, {"id": "u"}+ # Claude Code sends the title request, with structured output and no tools, first.+ title = {+ "model": "small",+ "max_tokens": 64,+ "messages": [{"role": "user", "content": "Find blue"}],+ "output_config": {"format": {"type": "json_schema", "schema": {"type": "object"}}},+ }+ result = await kernel.prepare(title, "anthropic", header, credential, upstream, policy)+ assert not result.tools_active+ body = request_body("anthropic", False)+ result = await kernel.prepare(body, "anthropic", header, credential, upstream, policy)+ assert result.tools_active+++async def test_client_openviking_tools_turn_gateway_tools_off(setup_kernel, credential, policy):+ kernel, store, _, _ = setup_kernel+ policy.update(gateway_tools=True, recall=False, capture=False)+ upstream = {"id": "u"}+ mcp = {"name": "mcp__ov__read", "description": "Read viking:// URIs", "input_schema": {}}+ body = request_body("anthropic", False)+ body["tools"].append(mcp)+ header = {"x-openviking-session": "client-ov"}+ result = await kernel.prepare(body, "anthropic", header, credential, upstream, policy)+ assert not result.tools_active+ assert result.metrics["tool_skip_reason"] == "tool_name_collision"++ # An MCP server that connects after the first turn turns them off for good.+ body = request_body("anthropic", False)+ header = {"x-openviking-session": "late-mcp"}+ first = await kernel.prepare(body, "anthropic", header, credential, upstream, policy)+ assert first.tools_active+ body["messages"] += [+ {"role": "assistant", "content": "Done"},+ {"role": "user", "content": "Why does mcp__openviking__search fail?"},+ ]+ assert (+ await kernel.prepare(body, "anthropic", header, credential, upstream, policy)+ ).tools_active+ body["tools"].append(mcp)+ later = await kernel.prepare(body, "anthropic", header, credential, upstream, policy)+ assert not later.tools_active+ body["tools"].pop()+ assert not (+ await kernel.prepare(body, "anthropic", header, credential, upstream, policy)+ ).tools_active++ # Once the model called a gateway tool, its history keeps the tools.+ body = request_body("anthropic", False)+ header = {"x-openviking-session": "used"}+ first = await kernel.prepare(body, "anthropic", header, credential, upstream, policy)+ await store.replay.put(+ first.scope,+ first.session,+ "hidden",+ first.body_chain[0],+ {"messages": [], "visible_count": 1},+ )+ body["tools"].append(mcp)+ kept = await kernel.prepare(body, "anthropic", header, credential, upstream, policy)+ assert kept.tools_active+ # Another branch turns them off, and the branch that used them still keeps them.+ other = request_body("anthropic", False)+ other["messages"][0]["content"] = "Find green"+ other["tools"].append(mcp)+ assert not (+ await kernel.prepare(other, "anthropic", header, credential, upstream, policy)+ ).tools_active+ kept = await kernel.prepare(body, "anthropic", header, credential, upstream, policy)+ assert kept.tools_active++ # A token count may cover only some of the client's tools and never turns them off.+ body = request_body("anthropic", False)+ header = {"x-openviking-session": "count"}+ assert (+ await kernel.prepare(body, "anthropic", header, credential, upstream, policy)+ ).tools_active+ counted = {**body, "tools": [mcp]}+ await kernel.prepare(counted, "anthropic", header, credential, upstream, policy, counting=True)+ assert (+ await kernel.prepare(body, "anthropic", header, credential, upstream, policy)+ ).tools_active++@pytest.mark.parametrize("arguments", [None, "", "{}", "{broken"])async def test_anthropic_stream_no_argument_tool(running_gateway, arguments):app, client, admin, key, _, _ = running_gatewaydiff --git a/tests/gateway/test_storage_ports.py b/tests/gateway/test_storage_ports.pyindex 406379151..27989a1e0 100644--- a/tests/gateway/test_storage_ports.py+++ b/tests/gateway/test_storage_ports.py@@ -198,6 +198,8 @@ async def test_kernel_and_capture_work_with_kv_ports(credential, protocol):K.ROOT,K.INJECTION,K.DISABLED,+ K.TOOLS,+ K.TOOLS_CLOSED,K.HIDDEN,K.REPLACEMENT,K.REPLY,diff --git a/web-studio/src/i18n/locales/en/gateway/enums.ts b/web-studio/src/i18n/locales/en/gateway/enums.tsindex 8e67bbb41..6310acb27 100644--- a/web-studio/src/i18n/locales/en/gateway/enums.ts+++ b/web-studio/src/i18n/locales/en/gateway/enums.ts@@ -65,11 +65,11 @@ const enums = {tools_forced_choice: 'The client required a specific tool',deepseek_reasoning_history_required:'DeepSeek thinking is on and earlier reasoning cannot be sent back',- tool_name_collision: 'The client defines a tool with the same name',+ tool_name_collision: 'The client already has OpenViking tools',tools_unavailable:- "OpenViking's tool list couldn't be loaded when this conversation started",+ "OpenViking's tool list couldn't be loaded when this conversation first needed it",tools_not_selected_at_session_start:- 'Tools were not available when this conversation started',+ 'This conversation has no OpenViking tools',},toolStopReason: {token_budget: 'Tool token budget reached',diff --git a/web-studio/src/i18n/locales/zh-CN/gateway/enums.ts b/web-studio/src/i18n/locales/zh-CN/gateway/enums.tsindex c8cc77c67..fa5d8d7c4 100644--- a/web-studio/src/i18n/locales/zh-CN/gateway/enums.ts+++ b/web-studio/src/i18n/locales/zh-CN/gateway/enums.ts@@ -63,9 +63,9 @@ const enums = {tools_forced_choice: '客户端指定了必须调用的工具',deepseek_reasoning_history_required:'DeepSeek 开启了思考模式,但之前回复的推理内容补不回来',- tool_name_collision: '客户端定义了同名工具',- tools_unavailable: '这段对话开始时无法加载 OpenViking 工具清单',- tools_not_selected_at_session_start: '这段对话开始时还没有启用工具',+ tool_name_collision: '客户端已接入 OpenViking 工具',+ tools_unavailable: '这段对话首次需要工具时无法加载 OpenViking 工具清单',+ tools_not_selected_at_session_start: '这段对话没有 OpenViking 工具',},toolStopReason: {token_budget: '工具 Token 预算已用完',