Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions docs/en/docs/integrations/langchain.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,49 @@ Configure Core and the gateway as well:
- Set `PC_GATEWAY_DEFAULT_SCOPE` to the Scope for requests without `X-PowerContext-Scope-ID`. If the application does
not send the header, set it to the Scope the middleware used, so that the gateway recalls the Memory captured before.

## Bind the Server's MCP tools on the Responses API

`PowerContextMiddleware` does not register the Server's MCP tools. An application that binds them itself to
`ChatOpenAI(use_responses_api=True)` must send them as non-strict function tools. By default LangChain leaves
`strict` out of every function tool. The Responses API applies strict mode to a function tool that omits the field,
and a request that carries the full PowerContext catalog can then fail: the provider answers HTTP 500, or HTTP 200
with a stream that ends in `response.failed`, and the model returns no answer.

`mcp_tool_definitions` turns the tools into function tool definitions that set `strict: false` and keep each input
schema unchanged. It accepts the tools an MCP client's `list_tools()` returns for the Server's `/mcp/` endpoint, and
LangChain tools built from them. Bind the definitions next to the application's own tools, which stay as they are:

```python
from langchain_openai import ChatOpenAI
from powercontext_langchain import mcp_tool_definitions

model = ChatOpenAI(model="gpt-4.1-mini", use_responses_api=True)
bound = model.bind_tools([*mcp_tool_definitions(mcp_tools), *application_tools])
```

`create_agent` binds its tools itself. Pass the executable MCP tools to the agent as usual and add
`McpToolDefinitionsMiddleware` with the same tools. For each model call it replaces those tools, by name, with their
non-strict definitions; the agent still executes the tools it was created with:

```python
from langchain.agents import create_agent
from powercontext_langchain import McpToolDefinitionsMiddleware

agent = create_agent(
model,
tools=[*mcp_tools, *application_tools],
middleware=[McpToolDefinitionsMiddleware(mcp_tools)],
)
```

Neither helper changes the application's other tools or their `strict` settings, and neither rewrites a schema to fit
strict mode. They are independent of `PowerContextMiddleware` and of the tools of the
[LangGraph adapter](langgraph.md).

[`integrations/langchain/examples/bind_mcp_tools.py`](https://github.com/oceanbase/powercontext/blob/master/integrations/langchain/examples/bind_mcp_tools.py)
is a runnable version of the first form that lists the catalog from a running Server and executes the MCP tools the
model calls.

## Failure behavior

Recall and capture are best-effort. Server unavailability, an invalid response, or request validation failure does not
Expand Down
41 changes: 41 additions & 0 deletions docs/zh/docs/integrations/langchain.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,47 @@ checkpointer 的 thread ID,长度为 1~256 个可见 ASCII 字符;不要
- 把 `PC_GATEWAY_DEFAULT_SCOPE` 设为不带 `X-PowerContext-Scope-ID` 的请求所用的 Scope。应用不发送该请求头时,
请把它设为 middleware 使用过的 Scope,使 gateway 能召回之前采集的 Memory。

## 在 Responses API 上绑定 Server 的 MCP 工具

`PowerContextMiddleware` 不会注册 Server 的 MCP 工具。如果应用自己把这些工具绑定到
`ChatOpenAI(use_responses_api=True)`,必须把它们作为非 strict 的函数工具发送。
LangChain 默认不给函数工具带 `strict` 字段。Responses API 会对缺少该字段的函数工具启用 strict 模式,
带有完整 PowerContext 工具目录的请求可能因此失败:服务端返回 HTTP 500,
或者返回 HTTP 200 但响应流以 `response.failed` 结束,模型没有给出回答。

`mcp_tool_definitions` 把这些工具转换成带 `strict: false` 的函数工具定义,输入 schema 保持不变。
它接受 MCP 客户端对 Server 的 `/mcp/` 端点调用 `list_tools()` 返回的工具,也接受由它们构造的 LangChain 工具。
把这些定义和应用自己的工具一起绑定即可,应用自己的工具保持原样:

```python
from langchain_openai import ChatOpenAI
from powercontext_langchain import mcp_tool_definitions

model = ChatOpenAI(model="gpt-4.1-mini", use_responses_api=True)
bound = model.bind_tools([*mcp_tool_definitions(mcp_tools), *application_tools])
```

`create_agent` 会自己绑定工具。照常把可执行的 MCP 工具传给 agent,再用同一批工具添加
`McpToolDefinitionsMiddleware`。每次模型调用时,它按名称把这些工具替换成非 strict 的定义;
agent 执行的仍然是创建时传入的工具:

```python
from langchain.agents import create_agent
from powercontext_langchain import McpToolDefinitionsMiddleware

agent = create_agent(
model,
tools=[*mcp_tools, *application_tools],
middleware=[McpToolDefinitionsMiddleware(mcp_tools)],
)
```

这两个入口都不改动应用的其他工具及其 `strict` 设置,也不会为了适配 strict 模式改写 schema。
它们与 `PowerContextMiddleware` 以及 [LangGraph 适配层](langgraph.md)自带的工具相互独立。

[`integrations/langchain/examples/bind_mcp_tools.py`](https://github.com/oceanbase/powercontext/blob/master/integrations/langchain/examples/bind_mcp_tools.py)
是第一种写法的可运行版本:它从运行中的 Server 列出工具目录,并执行模型调用的 MCP 工具。

## 故障行为

召回和采集都是 best-effort。Server 不可用、响应无效或请求校验失败时,不会替换模型回答或中止 agent。HTTP 401 和 403
Expand Down
21 changes: 21 additions & 0 deletions integrations/langchain/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,24 @@ remains enabled. Transport settings resolve from explicit values, host environme
`POWERCONTEXT_CLIENT_SERVER_URL` / `POWERCONTEXT_CLIENT_ALLOW_INSECURE_HTTP`, then the `langchain` entry in
`~/.config/powercontext/clients.json` (overridden by `POWERCONTEXT_CLIENT_CONFIG_FILE`). A host value of `false`
overrides common `true`. Saved consent applies only to its saved Server URL; changing a run's URL does not reuse it.

## Bind the Server's MCP tools

The middleware does not register the Server's MCP tools. When the application binds them itself on the OpenAI
Responses API, send them as non-strict function tools: the API applies strict mode to a tool that omits `strict`, and a
request that carries the full catalog can then fail. `mcp_tool_definitions` returns definitions that set
`strict: false` and keep each input schema; the application's other tools stay as they are.

```python
from powercontext_langchain import McpToolDefinitionsMiddleware, mcp_tool_definitions

bound = model.bind_tools([*mcp_tool_definitions(mcp_tools), *application_tools])

agent = create_agent(
model,
tools=[*mcp_tools, *application_tools],
middleware=[McpToolDefinitionsMiddleware(mcp_tools)],
)
```

[`examples/bind_mcp_tools.py`](examples/bind_mcp_tools.py) is a runnable version of the first form.
23 changes: 23 additions & 0 deletions integrations/langchain/examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Examples

Runnable examples for LangChain applications that use a PowerContext Server.

## `bind_mcp_tools.py`

Binds the Server's MCP tool catalog to `ChatOpenAI(use_responses_api=True)` and answers one prompt, executing the MCP
tools the model calls. The tools are bound through `mcp_tool_definitions` from `powercontext-langchain`, which sends
each one with `strict: false` and its input schema unchanged. By default LangChain leaves `strict` out of the request,
the Responses API applies strict mode to each function tool, and a request that carries the full catalog can fail.

The example is independent of `PowerContextMiddleware`, which does not register MCP tools. It needs a running Server
(`powercontext server run`), `powercontext-langchain`, `langchain-openai`, the `mcp` client, and an API key read from
the environment:

```bash
OPENAI_API_KEY=sk-... uv run --with langchain-openai --with mcp python \
integrations/langchain/examples/bind_mcp_tools.py "Which PowerContext Scope is the default?"
```

`POWERCONTEXT_MCP_URL` selects the MCP endpoint (default `http://127.0.0.1:8000/mcp/`),
`POWERCONTEXT_MCP_AUTHORIZATION` sets its Authorization header, `OPENAI_MODEL` selects the model (default
`gpt-4.1-mini`), and `OPENAI_BASE_URL` targets another provider of the Responses API.
81 changes: 81 additions & 0 deletions integrations/langchain/examples/bind_mcp_tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Copyright (c) 2026 OceanBase.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Bind the PowerContext Server's MCP tools to a LangChain model on the OpenAI Responses API.

The example lists the tool catalog of a running Server over MCP, binds every tool to ``ChatOpenAI`` with its JSON
Schema unchanged, and answers one prompt, executing the MCP tools the model calls. The tools are bound through
``mcp_tool_definitions``, which marks each one non-strict: when ``strict`` is left out, the Responses API applies
strict mode to each function tool and can fail a request that carries the full catalog. Run it against a Server
started with ``powercontext server run``::

OPENAI_API_KEY=sk-... uv run --with langchain-openai --with mcp python \
integrations/langchain/examples/bind_mcp_tools.py "Which PowerContext Scope is the default?"

``POWERCONTEXT_MCP_URL`` selects the Server's MCP endpoint, ``POWERCONTEXT_MCP_AUTHORIZATION`` its Authorization
header, and ``OPENAI_MODEL`` the model. ``OPENAI_BASE_URL`` targets another provider of the Responses API.
"""

from __future__ import annotations

import asyncio
import os
import sys
from collections.abc import Sequence

from langchain_core.language_models import LanguageModelInput
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, ToolMessage
from langchain_core.runnables import Runnable
from langchain_openai import ChatOpenAI
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
from mcp.types import TextContent, Tool
from powercontext_langchain import mcp_tool_definitions

MAX_MODEL_CALLS = 8


def bind_mcp_tools(model: ChatOpenAI, tools: Sequence[Tool]) -> Runnable[LanguageModelInput, AIMessage]:
"""Bind MCP tools as non-strict function tools that keep the Server's input schemas."""
return model.bind_tools(mcp_tool_definitions(tools))


async def answer(session: ClientSession, model: ChatOpenAI, prompt: str) -> str:
"""Answer one prompt, returning each MCP tool result to the model until it stops calling tools."""
bound = bind_mcp_tools(model, (await session.list_tools()).tools)
messages: list[BaseMessage] = [HumanMessage(prompt)]
for _ in range(MAX_MODEL_CALLS):
reply = await bound.ainvoke(messages)
if not reply.tool_calls:
return reply.text
messages.append(reply)
for call in reply.tool_calls:
result = await session.call_tool(call["name"], call["args"])
text = "\n".join(block.text for block in result.content if isinstance(block, TextContent))
messages.append(ToolMessage(text, tool_call_id=call["id"], status="error" if result.isError else "success"))
return "The model was still calling tools after the example's limit."


async def main(prompt: str) -> None:
url = os.environ.get("POWERCONTEXT_MCP_URL", "http://127.0.0.1:8000/mcp/")
authorization = os.environ.get("POWERCONTEXT_MCP_AUTHORIZATION")
headers = {"Authorization": authorization} if authorization else None
model = ChatOpenAI(model=os.environ.get("OPENAI_MODEL", "gpt-4.1-mini"), use_responses_api=True)
async with streamablehttp_client(url, headers=headers) as (read, write, _), ClientSession(read, write) as session:
await session.initialize()
print(await answer(session, model, prompt))


if __name__ == "__main__":
asyncio.run(main(" ".join(sys.argv[1:]) or "Which PowerContext Scope is the default?"))
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,15 @@

"""LangChain middleware integration for PowerContext durable memory."""

from .mcp_tools import McpToolDefinitionsMiddleware, mcp_tool_definitions
from .middleware import PowerContextMiddleware
from .scope import PowerContextScope
from .settings import PowerContextLangChainSettings

__all__ = [
"McpToolDefinitionsMiddleware",
"PowerContextLangChainSettings",
"PowerContextMiddleware",
"PowerContextScope",
"mcp_tool_definitions",
]
85 changes: 85 additions & 0 deletions integrations/langchain/src/powercontext_langchain/mcp_tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Copyright (c) 2026 OceanBase.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Bind the PowerContext Server's MCP tools to OpenAI-compatible models without strict mode."""

from __future__ import annotations

from collections.abc import Awaitable, Callable, Iterable
from typing import Any, Protocol

from langchain.agents.middleware.types import AgentMiddleware, ModelRequest, ModelResponse
from langchain_core.tools import BaseTool
from langchain_core.utils.function_calling import convert_to_openai_tool
from typing_extensions import override


class McpTool(Protocol):
"""The fields of an MCP ``Tool``, as an MCP client's ``list_tools`` returns it."""

name: str
description: str | None
inputSchema: dict[str, Any]


def mcp_tool_definitions(tools: Iterable[McpTool | BaseTool]) -> list[dict[str, Any]]:
"""Return non-strict function tool definitions that keep each tool's input schema.

The OpenAI Responses API applies strict mode to a function tool that omits ``strict``, and a request carrying the
Server's full MCP catalog can then fail. Each returned definition sets ``strict`` to false itself, so
``model.bind_tools([*mcp_tool_definitions(tools), *other_tools])`` leaves the other tools as the caller bound them.
"""
return [_definition(tool) for tool in tools]


class McpToolDefinitionsMiddleware(AgentMiddleware):
"""Send the given ``create_agent`` tools to the model as non-strict definitions.

``create_agent`` binds its tools itself, so the caller cannot choose their definitions. For each model call this
middleware replaces the given tools, by name, with their :func:`mcp_tool_definitions`. The agent still executes the
tools it was created with, and tools that were not given keep their definitions.
"""

def __init__(self, tools: Iterable[BaseTool]) -> None:
self._definitions = {tool.name: _definition(tool) for tool in tools}

@override
def wrap_model_call(
self,
request: ModelRequest[Any],
handler: Callable[[ModelRequest[Any]], ModelResponse[Any]],
) -> ModelResponse[Any]:
return handler(self._with_definitions(request))

@override
async def awrap_model_call(
self,
request: ModelRequest[Any],
handler: Callable[[ModelRequest[Any]], Awaitable[ModelResponse[Any]]],
) -> ModelResponse[Any]:
return await handler(self._with_definitions(request))

def _with_definitions(self, request: ModelRequest[Any]) -> ModelRequest[Any]:
tools = [
self._definitions.get(tool.name, tool) if isinstance(tool, BaseTool) else tool for tool in request.tools
]
return request.override(tools=tools)


def _definition(tool: McpTool | BaseTool) -> dict[str, Any]:
if isinstance(tool, BaseTool):
function = dict(convert_to_openai_tool(tool)["function"])
else:
function = {"name": tool.name, "description": tool.description or "", "parameters": tool.inputSchema}
return {"type": "function", "function": {**function, "strict": False}}
Loading
Loading