Skip to content

fix(runtime): carry the tool name onto LangChain ToolMessage - #7327

Merged
lukasmoschitz merged 2 commits into
CopilotKit:mainfrom
Ash20pk:fix/langchain-toolmessage-name
Oct 28, 2026
Merged

lukasmoschitz merged 2 commits into
CopilotKit:mainfrom
Ash20pk:fix/langchain-toolmessage-name

Conversation

@Ash20pk

@Ash20pk Ash20pk commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Picks up the second half of #6571, the part #6586 deliberately left alone.

The bug

convertMessageToLangChainMessage builds a ToolMessage from a ResultMessage and drops the tool's identity on the floor:

// packages/runtime/src/v1-deprecated/service-adapters/langchain/utils.ts (before)
} else if (message.isResultMessage()) {
  return new ToolMessage({
    content: message.result,
    tool_call_id: message.actionExecutionId,
  });
}

ResultMessage already carries actionName. It just never gets passed.

The two halves of the same round trip disagree about this. The ActionExecutionMessage branch twenty lines up already passes name through onto the AIMessage's tool call, so a chain sees the name on the way out and then loses it on the way back.

Why it matters

ToolMessage.name is the field LangChain consumers route on. With it unset, a chain behind LangChainAdapter that matches on tool identity falls through silently. Nothing throws, nothing logs, the branch just never runs and the model carries on as if it had. That is the same failure shape #6571 describes: the evidence of a working gate and the evidence of a gate that never fired are identical from inside the app.

The only workaround available to a consumer is to walk back through the message list to the ActionExecutionMessage whose id matches tool_call_id and read the name off that. That is work the adapter is better placed to do, and it is exactly the lookup sdk-python/copilotkit/copilotkit_lg_middleware.py:840 already does on the Python side, where name is set correctly from the matching tool call. This brings the TypeScript adapter in line with it.

The fix

One field, plus a comment saying why it's there.

Tests

New utils.test.ts, four specs. Two pin the name, two guard against collateral damage:

  • name is carried onto the ToolMessage
  • tool_call_id and content are untouched
  • the name round-trips: convertedResult.name equals the name on the AIMessage's tool call produced from the matching ActionExecutionMessage
  • text messages still convert to HumanMessage

Reverting only utils.ts and keeping the specs fails the two that pin the name (expected undefined to be 'request_page_oncall') and passes the other two, so they bind to the mechanism rather than to themselves.

Differential full-suite run on packages/runtime, with and without the change: identical failure set either way (105 files / 8 tests, all pre-existing and all from workspace deps that aren't built in a fresh checkout — Cannot find module '@copilotkit/shared/...' and friends). The change adds exactly one passing file and four passing tests and moves nothing else. tsc --noEmit reports no errors in either touched file; the 35 it does report are the same unbuilt-dependency errors and are present on clean main.

Scope

convertMessageToLangChainMessage has one caller, langchain-adapter.ts:106. Nothing reads ToolMessage.name inside this repo, so nothing here depended on it being unset.

This is a behavior change for anyone downstream who had worked around the gap by reading the name out of the message list themselves. Their workaround keeps working, since it reads the ActionExecutionMessage, not this field. Worth a release note anyway.

Still not addressed

The upstream half. @ag-ui/langgraph's aguiMessagesToLangChain() omits name in its case "tool", and the root cause is that ToolMessageSchema in @ag-ui/core is the only message role without a name field. That is not fixed in 0.0.43 — that release only added status — so bumping the 0.0.42 pin in packages/runtime/package.json and packages/sdk-js/package.json will not help. It needs a change in those packages, not this one.

One correction to a note I left on #6586: I flagged examples/showcases/scene-creator/agent/agent.py:743 as a live instance of this bug. It isn't. The tools it routes on are backend tools executed by LangGraph's ToolNode, which sets name itself, so that read is fine. My mistake.

Summary by CodeRabbit

  • Bug Fixes
    • Tool results now retain the originating action name when converted to LangChain messages.
    • Consumers can identify which tool produced a result directly from the converted message.
    • Added coverage to verify tool identifiers, content, and text message conversions remain intact.

convertMessageToLangChainMessage built a ToolMessage from a ResultMessage
with only content and tool_call_id, dropping actionName. ToolMessage.name is
the field LangChain consumers route on, so any chain behind LangChainAdapter
that matched on tool identity fell through silently: the gated branch never
ran, and nothing errored.

ResultMessage already carries actionName, and the sibling branch for
ActionExecutionMessage already passes name through, so the two halves of the
same round trip disagreed. Pass it through on the result side too.

Adds utils.test.ts: two specs pin the name (they fail with this change
reverted) and two guard tool_call_id, content and the text-message branch
against regressing.

Refs CopilotKit#6571
@coderabbitai

coderabbitai Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Understand this PR’s impact

Explore downstream dependencies and potential security impact with Blast Radius.

View blast radius →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

⚙️ Run configuration

Configuration used: Repository: CopilotKit/CopilotKit/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 189f8613-99a7-4681-92aa-7490342fbadf

📥 Commits

Reviewing files that changed from the base of the PR and between f94908c and d7ebb82.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: CopilotKit/CopilotKit/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: dd178ac5-32ce-4dda-8255-edc9129cb514

📥 Commits

Reviewing files that changed from the base of the PR and between 0048ba2 and f94908c.

📒 Files selected for processing (2)
  • packages/runtime/src/v1-deprecated/service-adapters/langchain/utils.test.ts
  • packages/runtime/src/v1-deprecated/service-adapters/langchain/utils.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

The LangChain adapter now assigns message.actionName to the name field of converted ToolMessage results. Tests cover tool identity, metadata, content preservation, originating action names, and text conversion.

Changes

LangChain message conversion

Layer / File(s) Summary
Preserve tool identity in result conversion
packages/runtime/src/v1-deprecated/service-adapters/langchain/utils.ts, packages/runtime/src/v1-deprecated/service-adapters/langchain/utils.test.ts
Result messages now produce ToolMessage objects with the originating action name. Tests verify the name, tool_call_id, content, action-name round trip, and TextMessage conversion.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: carrying the tool name onto the LangChain ToolMessage.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

BenTaylorDev added a commit that referenced this pull request Oct 26, 2026
…in (#7756)

Closes #3217. Refs #6408 (item 11).

## Problem

Since v1.50.0, `handleServiceAdapter` turns a v1 service adapter into a
`BuiltInAgent`. That works only when the adapter can name a model
through `getLanguageModel()` or a `provider/model` pair that
BuiltInAgent can resolve. `serviceAdapter.process()` has no callers on
`main`, so any adapter whose behavior lives in `process()` had no
execution path:

- `LangChainAdapter`: the custom `chainFn` never runs. On `main` the
runtime advertises **no agents** (`/info` returns `"agents":{}`), and a
v1 app's page crashes with `useAgent: Agent 'default' not found after
runtime sync`.
- `BedrockAdapter` extends `LangChainAdapter` and sets `provider =
"bedrock"`. It reached the `provider/model` branch, and BuiltInAgent has
no `bedrock` provider.
- User-written `CopilotServiceAdapter`s failed the same way.

v1 is deprecated, but it will not be deleted. The deprecation exists to
stop new adoption, not to strand existing users. Runtime telemetry
(`oss.runtime.instance_created`, last 30 days) shows about 3,400
distinct IDs that use `LangChainAdapter` on 1.10.x, and about 30 on
1.50+ that hit the error.

**A second regression is fixed here too (commit `e7434e7`).** Since
#7157 (v1.73.1), no v1 `actions` or `mcpServers` tool reaches *any*
agent, BuiltInAgent included, through a documented v1 endpoint. Every
endpoint calls `getRuntimeInstanceTelemetryInfo` before
`handleServiceAdapter`, and that function read
`runtime.instance.agents`. Reading it built the v2 runtime early, so the
per-request factory that attaches the tools was never used. The tests in
#7157 and #6931 wired the endpoint by hand, so they never ran that call
first. I found it in the real app below. It can be split into its own PR
if you prefer.

## Fix

`LegacyServiceAdapterAgent`
(`lib/runtime/legacy-service-adapter-agent.ts`) is an `AbstractAgent`
that runs the adapter's own `process()`:

- **Input:** AG-UI messages become v1 messages through the runtime's
`aguiToGQL`. `input.tools` become `ActionInput[]`. `input.context`
becomes a leading system message, which is where the v1 frontend put
readable context.
- **Events:** the bridge captures the `eventSource.stream` callback (its
consumer was deleted in v1.50.0) and maps runtime events to AG-UI
`TEXT_MESSAGE_*`, `TOOL_CALL_*` and `TOOL_CALL_RESULT`, inside
`RUN_STARTED`/`RUN_FINISHED`. A failure becomes `RUN_ERROR`.
- **Server-side v1 `actions` and `mcpServers`** arrive as
`config.tools`, as on BuiltInAgent. The bridge advertises them to the
adapter, executes them, and calls `process()` again with the results, up
to 10 steps. A frontend tool call ends the run.
- **Stop:** `abortRun()` aborts the run, as on BuiltInAgent. No further
step or server tool runs, and the LangChain model stream is cancelled so
that it does not keep streaming and billing.

LangChain fixes that the bridge makes reachable (the GraphQL path never
ran `verifyEvents`, so the old defects did not fail a turn):

- A plain `string` returned by `chainFn` always threw, because the code
read `actionExecution.id` off `undefined`. This was already the case in
1.10.6.
- With parallel tool calls on the streaming path, the code ended the
*new* call's id instead of the open one, so the run failed with
`RUN_ERROR`. A stream that ended inside a tool call ended `undefined`.
- After a parallel tool call, OpenAI rejected the next model call with a
400. Each call had become its own `AIMessage`, and an assistant
tool-call message must be followed directly by its results.
`LangChainAdapter` now folds each assistant turn back into one message.
- Anthropic-style array content reached `TEXT_MESSAGE_CONTENT` as an
array. Only the text parts are sent now.

Routing in `ensureDefaultAgent` changes only for cases that fail today:

| Adapter exposes | Before | After |
|---|---|---|
| `getLanguageModel()` | BuiltInAgent | unchanged |
| `provider/model` that `resolveModel` accepts | BuiltInAgent |
unchanged |
| `provider/model` that `resolveModel` rejects (`bedrock`) |
BuiltInAgent that throws on first run | bridge |
| neither | `CopilotKitMisuseError` | bridge |
| `OpenAIAssistantAdapter` | `CopilotKitMisuseError` | a clear
`CopilotKitMisuseError` |

`OpenAIAssistantAdapter` stays on an error on purpose. Its `process()`
needs OpenAI thread and run ids carried between requests, and OpenAI
shut down the Assistants API on 2026-08-26.

`copilot-runtime.ts` does not import `LangChainAdapter`, because
`@langchain/core` is an optional peer. No public API is added.
`RuntimeEventSubject` gains an optional `signal` constructor argument,
and the public API manifest check passes. `agentsAmount` in v1 endpoint
telemetry now reports the configured count; it was always 0 before.

## Testing

### Real app, before and after

`examples/v1/next-openai`, the v1 `CopilotSidebar` page with
`copilotRuntimeNextJSAppRouterEndpoint`, driven in a browser. I added a
local-only `langchain_openai` case (not committed) that uses the
documented `model.bindTools(tools).stream(messages)` with `gpt-4o-mini`.

- **`main` runtime:** `/info` returns `"agents":{}`. The page crashes
with `useAgent: Agent 'default' not found after runtime sync … No agents
registered`.
- **This branch:** `/info` lists `default` as a
`LegacyServiceAdapterAgent`.
- **Parallel server-side actions:** prompt "get image urls for
lighthouse and mountain (one call per topic, in parallel)". `chainFn`
call 1 received `getImageUrl`, both calls ran on the server, and call 2
received a 5-message history (user, one merged assistant turn, two tool
results). The model answered with both URLs.
- **Frontend tool:** "Add Lisbon to the new destinations".
`AddNewDestination` ran in the browser, the row appeared, and the
follow-up run answered "Lisbon, Portugal has been added". No loop.

### Stop, through the real endpoint

A model stream produces one chunk every 100 ms. `agent/stop` is called
after 1 s:

```
before the cancel fix: response ended at 1020ms | model chunks at stop: 9, 1.5s later: 24 | stream cancelled: false
after:                 response ended at 1019ms | model chunks at stop: 9, 1.5s later: 10 | stream cancelled: true
```

### Live OpenAI runs (`gpt-4o-mini`, local only, not committed)

```
✓ parallel server-side tools, then a second step     (failed before the fix: 400 "An assistant message with 'tool_calls' must be followed by tool messages…")
✓ follow-up after parallel frontend tool results     (failed before the fix: same 400)
✓ single server tool still works
✓ text / server action loop / frontend tool / follow-up   (first round)
```

### Unit and end-to-end tests

The end-to-end tests send a real `LangChainAdapter` through `POST
agent/run` on the single-route endpoint and parse the SSE stream.
`v1-endpoint-order.test.ts` copies the real endpoints' order (telemetry
first, then `handleServiceAdapter`). I wrote each new test before its
fix and confirmed it fails without the fix:

| Test | Fails when |
|---|---|
| parallel tool calls close in order; stream ends inside a call | the
end uses the chunk's id |
| parallel tool calls reach `chainFn` as one `AIMessage` | there is no
merge |
| array content streams its text | content is cast to string |
| Stop completes a run whose stream never ends | `abortRun` does
nothing, or there is no abort listener |
| Stop cancels the LangChain model stream | there is no cancel on abort
|
| telemetry does not build the instance; v1 actions reach the agent |
telemetry reads `runtime.instance` |
| routing: LangChain / Bedrock / provider without model → bridge;
Assistant → clear error | routing is reverted |

```
nx run @copilotkit/runtime:test         Test Files 199 passed | Tests 2933 passed
nx run @copilotkit/runtime:check-types  exit 0
nx run @copilotkit/runtime:build        exit 0
pnpm check:public-api-manifest          manifest.v1.json is current
```

## Review

An adversarial review of the first version found the parallel-tool-call,
Stop, array-content, and OpenAIAssistantAdapter defects. I reproduced
each one before fixing it. The browser run then found the #7157
telemetry regression, and a probe found the stream that was not
cancelled.

## Not verified

- I did not run `BedrockAdapter` live (no AWS credentials). It routes
through the same LangChain path that I tested.
- Agent-state and LangGraph meta events are not mapped. Only remote
agent endpoints emitted them.
- When v1 `actions` are in use, the suggestion feature runs through the
bridge. It ignores `forwardedProps.toolChoice`, as v1's
`LangChainAdapter` always did, because `chainFn` owns the model call.

## Seen while testing, not caused by this PR

`examples/v1/next-openai` sends hundreds of runtime POSTs per minute on
`main` with *any* adapter (689 in 25 s with `OpenAIAdapter`). `/multi`
throws `Invalid action configuration`, and `runtimeUrl` with a query
string produces `…?serviceAdapter=x/info` (405). Worth a separate look.

## Overlap

#7327 and #7740 change `convertMessageToLangChainMessage` in
`langchain/utils.ts`, in a different function. Both #7740 and #7327
merge cleanly with the current head.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added support for running legacy service adapters through the agent
runtime, including frontend and server-side tools.
* Added improved handling for tool arguments, context, streaming, and
cancellation.

* **Bug Fixes**
  * Improved compatibility with adapters that do not specify a model.
* Fixed LangChain tool calls, message content, streamed responses, and
parallel tool-call ordering.
* Aborting a run now cancels active streams and prevents further
processing.
* Requests using the retired OpenAI Assistants API now receive a clear
shutdown error.
* Improved endpoint action handling, telemetry counts, validation, and
error reporting.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

@lukasmoschitz lukasmoschitz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is the first open item Ben listed on #6571. Checked against current main: both name tests fail without the change and pass with it, the rest of the LangChain adapter tests and the runtime type check are green. #6571 stays open for the example and the docs.

@lukasmoschitz
lukasmoschitz added this pull request to the merge queue Oct 28, 2026
Merged via the queue into CopilotKit:main with commit e1281c7 Oct 28, 2026
70 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants