Skip to content

Conversation

@ahmedrowaihi
Copy link

@ahmedrowaihi ahmedrowaihi commented Dec 5, 2025

🎯 Changes

Supporting context in tool execution..

to make tools behaviour context aware, the only way is to reconstruct them everytime you want to invoke a new trigger..
this PR suggests supporting context.

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested this code locally with pnpm run test:pr.
  • I have tested this code locally with pnpm run test:lib.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Summary by CodeRabbit

Release Notes

  • New Features

    • Tools now support shared context during execution, enabling stateful operations across both client and server environments.
    • Chat operations can pass context to tools for enhanced functionality and data access.
  • Tests

    • Added comprehensive test coverage for context propagation in tool execution across client and server scenarios.
    • Updated existing tests to validate context parameter handling.

✏️ Tip: You can customize this high-level summary in your review settings.

@ahmedrowaihi
Copy link
Author

this was my initial thought, feel free to suggest enhancement or if there is a better way

@AlemTuzlak AlemTuzlak requested a review from jherr December 5, 2025 14:47
Copy link
Contributor

@jherr jherr left a comment

Choose a reason for hiding this comment

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

One small API change, otherwise I love it!

@ahmedrowaihi
Copy link
Author

hey @jherr , thanks for this suggestion ! yes it's much better to make this prop scalable..
now I think we can later on different PR add Tool Hooks ! that would be cool feature..
for example, compressing tool results hook ? yeah why not

@nx-cloud
Copy link

nx-cloud bot commented Dec 5, 2025

View your CI Pipeline Execution ↗ for commit c818617

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... ✅ Succeeded 1m 16s View ↗
nx run-many --targets=build --exclude=examples/** ✅ Succeeded 29s View ↗

☁️ Nx Cloud last updated this comment at 2025-12-05 15:40:42 UTC

@AlemTuzlak
Copy link
Contributor

I have 2 questions on my mind here:

  • do we want to send the context in between the two
  • how do we type the tools to have the context they need

@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 5, 2025

Open in StackBlitz

@tanstack/ai

npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai@93

@tanstack/ai-anthropic

npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-anthropic@93

@tanstack/ai-client

npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-client@93

@tanstack/ai-devtools-core

npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-devtools-core@93

@tanstack/ai-gemini

npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-gemini@93

@tanstack/ai-ollama

npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-ollama@93

@tanstack/ai-openai

npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openai@93

@tanstack/ai-react

npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react@93

@tanstack/ai-react-ui

npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react-ui@93

@tanstack/ai-solid

npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid@93

@tanstack/ai-solid-ui

npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid-ui@93

@tanstack/react-ai-devtools

npm i https://pkg.pr.new/TanStack/ai/@tanstack/react-ai-devtools@93

@tanstack/solid-ai-devtools

npm i https://pkg.pr.new/TanStack/ai/@tanstack/solid-ai-devtools@93

commit: c818617

@ahmedrowaihi
Copy link
Author

ahmedrowaihi commented Dec 5, 2025

  • do we want to send the context in between the two

hey @AlemTuzlak ..
was just removing this, seemed stale code...

.server() will have server context
.client() will have client context

isomorphic context :'D

@ahmedrowaihi
Copy link
Author

@AlemTuzlak , do you think we better also pass current serialisable_only within the request ?

@ahmedrowaihi
Copy link
Author

how do we type the tools to have the context they need

getToolDef.server<{ userId: string }> will make server.options.context.userId typesafe, same goes to client tools.

do we want to send the context in between the two

I think that was bad initial idea, or maybe not and we can make use of it but only serialisable will be sent

@ahmedrowaihi
Copy link
Author

@jherr @AlemTuzlak anything is missing here 👀 ? would love to fix or enhance if any

@coderabbitai
Copy link

coderabbitai bot commented Dec 18, 2025

Walkthrough

This PR introduces context support throughout the TanStack AI framework by adding a generic context parameter to tool definitions, chat options, and execution flows. Context is threaded from chat initialization through tool execution chains on both server and client sides, enabling context-aware tool behavior while maintaining backward compatibility.

Changes

Cohort / File(s) Summary
Type System & Tool Infrastructure
packages/typescript/ai/src/types.ts, packages/typescript/ai/src/tools/tool-definition.ts, packages/typescript/ai-client/src/types.ts
Introduced ToolOptions<TContext> interface and added generic context parameter to Tool, ChatOptions, ServerTool, and ClientTool interfaces. Updated tool execute signatures to accept (args, options: ToolOptions<TContext>) parameters. Added context?: TContext property to ChatOptions and ChatClientOptions.
Chat Engine & Tool Execution
packages/typescript/ai/src/core/chat.ts, packages/typescript/ai/src/tools/tool-calls.ts, packages/typescript/ai-client/src/chat-client.ts
Extended ChatEngine with private options field for context. Updated ToolCallManager.executeTools() and executeToolCalls() to accept and propagate context via options parameter. Made ChatClient generic over tools and context, passing context to client-side tool execution via tool.execute(input, { context }).
Test Suites
packages/typescript/ai/tests/*.test.ts, packages/typescript/ai-client/tests/chat-client.test.ts
Updated existing tests to pass context parameter to tool execute calls. Added new test suites validating context propagation in tool execution and verifying tools work without context (optional behavior).
Example Application
examples/ts-react-chat/src/routes/api.tanchat.ts
Updated addToCartToolServer handler signature to accept (args, options) and expanded return value with quantity and totalItems fields. Introduced serverContext object and passed it to chat stream via context parameter.

Sequence Diagram

sequenceDiagram
    participant Client
    participant ChatEngine
    participant ToolCallMgr
    participant Tool

    Client->>ChatEngine: new ChatEngine({<br/>context: myContext<br/>})
    Note over ChatEngine: Store options with context
    
    Client->>ChatEngine: processMessage(msg)
    ChatEngine->>ChatEngine: checkForPendingToolCalls()<br/>(pass this.options)
    
    ChatEngine->>ToolCallMgr: executeToolCalls(tools, options)
    Note over ToolCallMgr: Receive options with context
    
    ToolCallMgr->>Tool: execute(args,<br/>{ context: myContext })
    Tool->>Tool: Access context for execution
    Tool-->>ToolCallMgr: result
    ToolCallMgr-->>ChatEngine: toolResults[]
    ChatEngine-->>Client: response
    
    Note over Client,Tool: Context flows through<br/>entire execution chain
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Areas requiring extra attention:

  • Generic type parameters: The new TContext generics threaded through ToolDefinition, ChatOptions, ChatClient, and related types create interdependencies; verify consistency across all generic bounds and constraints
  • Execute signature changes: Tool execute callbacks now require a second options parameter across server and client tools—validate that all tool invocations throughout the codebase pass the correct parameter
  • Tool type inference: The ClientTool union expansion from 2 to 4 type parameters and the AnyClientTool union updates may impact type checking; confirm no regressions in tool type narrowing
  • Context propagation paths: Multiple execution paths (normal tools, pre-approved tools, client-executed tools) now thread context; ensure no path is missed or incorrectly typed
  • Test coverage: While existing tests were updated with context parameters, verify that edge cases (missing context, null context, context type mismatches) are adequately covered

Poem

🐰 Through tools we hop, with context so deep,
Each execution now knows what to keep,
From server to client, the context flows true,
With generics and options, we know what to do,
No more lost parameters—our pathway is clear! 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Description check ❓ Inconclusive The description includes the required 'Changes' section explaining context support and completed checklists, but the 'Release Impact' section lacks a changeset despite modifying published code. Clarify whether this requires a changeset by checking if changes are part of published packages. If so, add a changeset using the provided documentation link.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: context aware tools' directly summarizes the main change: adding context-aware capabilities to the tool execution system across multiple packages.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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 and usage tips.

feat: introduce ToolOptions and update tool execution context

fix: update context handling in ChatClient and API route
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (5)
packages/typescript/ai/tests/tool-definition.test.ts (1)

63-71: Consider removing as any type assertion.

The { context: undefined as any } assertion works but bypasses type checking. Since ToolOptions<TContext> accepts unknown by default and context is optional, you could simply use { context: undefined } without the assertion.

🔎 Suggested fix
-      const result = await serverTool.execute(
-        { location: 'Paris' },
-        { context: undefined as any },
-      )
+      const result = await serverTool.execute(
+        { location: 'Paris' },
+        { context: undefined },
+      )
       expect(result).toEqual({ temperature: 72, conditions: 'sunny' })
-      expect(executeFn).toHaveBeenCalledWith(
-        { location: 'Paris' },
-        { context: undefined as any },
-      )
+      expect(executeFn).toHaveBeenCalledWith(
+        { location: 'Paris' },
+        { context: undefined },
+      )
examples/ts-react-chat/src/routes/api.tanchat.ts (1)

39-45: Unused options parameter in server tool handler.

The options parameter is declared but not used in the handler. If context isn't needed here currently, consider using _options to indicate intentional non-use, or remove it until needed.

🔎 Suggested change:
-const addToCartToolServer = addToCartToolDef.server((args, options) => ({
+const addToCartToolServer = addToCartToolDef.server((args, _options) => ({
   success: true,
   cartId: 'CART_' + Date.now(),
   guitarId: args.guitarId,
   quantity: args.quantity,
   totalItems: args.quantity,
 }))
packages/typescript/ai-client/tests/chat-client.test.ts (1)

612-624: Simplify the generic type annotation in the mock function.

The generic <TContext = unknown> on the mock function is unusual since the function is immediately specialized for TestContext. Consider simplifying the type annotation.

🔎 Suggested simplification:
       const executeFn = vi.fn(
-        async <TContext = unknown>(
-          _args: any,
-          options: ToolOptions<TContext>,
-        ) => {
-          const ctx = options.context as TestContext
+        async (_args: any, options: ToolOptions<TestContext>) => {
+          const ctx = options.context!
           ctx.localStorage.setItem(
             `pref_${ctx.userId}_${_args.key}`,
             _args.value,
           )
           return { success: true }
         },
       )
packages/typescript/ai-client/src/chat-client.ts (1)

500-533: Consider adding context to updateOptions for dynamic context updates.

The updateOptions method doesn't currently support updating context. If context needs to change during the client's lifetime (e.g., when user session changes), this would require recreating the client. Consider if this is the intended behavior.

packages/typescript/ai/src/tools/tool-definition.ts (1)

197-223: Consider narrowing the as any cast for better type safety.

The execute as any casts at lines 207 and 221 bypass type checking. While this works correctly at runtime since the execute function passed in has the correct signature, it could mask future type mismatches during refactoring.

A slightly safer alternative would be to use a more targeted type assertion that preserves the function shape:

🔎 Suggested improvement
       return {
         __toolSide: 'server',
         __contextType: undefined as TContext,
         ...config,
-        execute: execute as any,
+        execute: execute as Tool<TInput, TOutput, TName>['execute'],
       }

Similarly for the client method. This maintains the function signature while allowing the TContext variance.

That said, given the complexity of the generic variance involved, the current approach is pragmatic and acceptable for a "Chill" review.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e011bf8 and 8e92c0e.

📒 Files selected for processing (11)
  • examples/ts-react-chat/src/routes/api.tanchat.ts (3 hunks)
  • packages/typescript/ai-client/src/chat-client.ts (4 hunks)
  • packages/typescript/ai-client/src/types.ts (2 hunks)
  • packages/typescript/ai-client/tests/chat-client.test.ts (3 hunks)
  • packages/typescript/ai/src/core/chat.ts (5 hunks)
  • packages/typescript/ai/src/tools/tool-calls.ts (7 hunks)
  • packages/typescript/ai/src/tools/tool-definition.ts (7 hunks)
  • packages/typescript/ai/src/types.ts (4 hunks)
  • packages/typescript/ai/tests/ai-chat.test.ts (6 hunks)
  • packages/typescript/ai/tests/tool-call-manager.test.ts (1 hunks)
  • packages/typescript/ai/tests/tool-definition.test.ts (6 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from /adapters subpath rather than monolithic adapters
Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions with toolDefinition() and Zod schema inference
Implement isomorphic tool system using toolDefinition() with .server() and .client() implementations for dual-environment execution
Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safety
Implement stream processing with StreamProcessor for handling chunked responses and support partial JSON parsing for streaming AI responses

Files:

  • packages/typescript/ai/tests/tool-call-manager.test.ts
  • packages/typescript/ai/src/tools/tool-calls.ts
  • packages/typescript/ai/tests/ai-chat.test.ts
  • packages/typescript/ai-client/src/chat-client.ts
  • packages/typescript/ai/src/core/chat.ts
  • examples/ts-react-chat/src/routes/api.tanchat.ts
  • packages/typescript/ai-client/src/types.ts
  • packages/typescript/ai/tests/tool-definition.test.ts
  • packages/typescript/ai-client/tests/chat-client.test.ts
  • packages/typescript/ai/src/types.ts
  • packages/typescript/ai/src/tools/tool-definition.ts
**/*.test.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Write unit tests using Vitest alongside source files with .test.ts naming convention

Files:

  • packages/typescript/ai/tests/tool-call-manager.test.ts
  • packages/typescript/ai/tests/ai-chat.test.ts
  • packages/typescript/ai/tests/tool-definition.test.ts
  • packages/typescript/ai-client/tests/chat-client.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Use camelCase for function and variable names throughout the codebase

Files:

  • packages/typescript/ai/tests/tool-call-manager.test.ts
  • packages/typescript/ai/src/tools/tool-calls.ts
  • packages/typescript/ai/tests/ai-chat.test.ts
  • packages/typescript/ai-client/src/chat-client.ts
  • packages/typescript/ai/src/core/chat.ts
  • examples/ts-react-chat/src/routes/api.tanchat.ts
  • packages/typescript/ai-client/src/types.ts
  • packages/typescript/ai/tests/tool-definition.test.ts
  • packages/typescript/ai-client/tests/chat-client.test.ts
  • packages/typescript/ai/src/types.ts
  • packages/typescript/ai/src/tools/tool-definition.ts
examples/**

📄 CodeRabbit inference engine (CLAUDE.md)

Examples are not built by Nx and should be run independently from their directories with pnpm dev or pnpm install && pnpm dev

Files:

  • examples/ts-react-chat/src/routes/api.tanchat.ts
🧠 Learnings (10)
📓 Common learnings
Learnt from: CR
Repo: TanStack/ai PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-13T17:09:09.794Z
Learning: Implement framework integrations using the headless `tanstack/ai-client` for state management with framework-specific hooks (useChat) on top
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR
Repo: TanStack/ai PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-13T17:09:09.794Z
Learning: Applies to **/*.{ts,tsx} : Implement isomorphic tool system using `toolDefinition()` with `.server()` and `.client()` implementations for dual-environment execution

Applied to files:

  • packages/typescript/ai/tests/tool-call-manager.test.ts
  • packages/typescript/ai/src/tools/tool-calls.ts
  • packages/typescript/ai/tests/ai-chat.test.ts
  • packages/typescript/ai-client/src/chat-client.ts
  • packages/typescript/ai/tests/tool-definition.test.ts
  • packages/typescript/ai-client/tests/chat-client.test.ts
  • packages/typescript/ai/src/types.ts
  • packages/typescript/ai/src/tools/tool-definition.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR
Repo: TanStack/ai PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-13T17:09:09.794Z
Learning: Applies to **/*.{ts,tsx} : Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions with `toolDefinition()` and Zod schema inference

Applied to files:

  • packages/typescript/ai/src/tools/tool-calls.ts
  • packages/typescript/ai/tests/tool-definition.test.ts
  • packages/typescript/ai/src/types.ts
  • packages/typescript/ai/src/tools/tool-definition.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR
Repo: TanStack/ai PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-13T17:09:09.794Z
Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shaking

Applied to files:

  • packages/typescript/ai/tests/ai-chat.test.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR
Repo: TanStack/ai PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-13T17:09:09.794Z
Learning: Applies to **/*.{ts,tsx} : Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from `/adapters` subpath rather than monolithic adapters

Applied to files:

  • packages/typescript/ai/tests/ai-chat.test.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR
Repo: TanStack/ai PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-13T17:09:09.794Z
Learning: Applies to **/*.{ts,tsx} : Implement stream processing with StreamProcessor for handling chunked responses and support partial JSON parsing for streaming AI responses

Applied to files:

  • packages/typescript/ai/tests/ai-chat.test.ts
  • packages/typescript/ai/src/types.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR
Repo: TanStack/ai PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-13T17:09:09.794Z
Learning: Implement framework integrations using the headless `tanstack/ai-client` for state management with framework-specific hooks (useChat) on top

Applied to files:

  • packages/typescript/ai-client/src/chat-client.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR
Repo: TanStack/ai PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-13T17:09:09.794Z
Learning: Applies to **/*.test.ts : Write unit tests using Vitest alongside source files with `.test.ts` naming convention

Applied to files:

  • packages/typescript/ai/tests/tool-definition.test.ts
  • packages/typescript/ai-client/tests/chat-client.test.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR
Repo: TanStack/ai PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-13T17:09:09.794Z
Learning: Applies to **/*.{ts,tsx} : Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safety

Applied to files:

  • packages/typescript/ai/src/types.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR
Repo: TanStack/ai PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-13T17:09:09.794Z
Learning: Applies to packages/typescript/*/src/model-meta.ts : Maintain model metadata files that define provider options and capabilities per model for per-model type safety

Applied to files:

  • packages/typescript/ai/src/types.ts
🧬 Code graph analysis (7)
packages/typescript/ai/src/tools/tool-calls.ts (1)
packages/typescript/ai/src/types.ts (3)
  • ToolOptions (75-77)
  • ToolCall (62-69)
  • Tool (328-434)
packages/typescript/ai/tests/ai-chat.test.ts (1)
packages/typescript/ai/src/types.ts (3)
  • ToolOptions (75-77)
  • Tool (328-434)
  • ChatOptions (561-619)
packages/typescript/ai-client/src/chat-client.ts (3)
packages/typescript/ai/src/tools/tool-definition.ts (1)
  • AnyClientTool (60-62)
packages/typescript/ai/src/types.ts (1)
  • ToolOptions (75-77)
packages/typescript/ai-client/src/types.ts (1)
  • ChatClientOptions (134-230)
packages/typescript/ai/src/core/chat.ts (1)
packages/typescript/ai/src/types.ts (1)
  • ToolOptions (75-77)
examples/ts-react-chat/src/routes/api.tanchat.ts (2)
examples/ts-solid-chat/src/lib/guitar-tools.ts (1)
  • addToCartToolServer (109-117)
examples/ts-react-chat/src/lib/guitar-tools.ts (1)
  • addToCartToolDef (69-84)
packages/typescript/ai/tests/tool-definition.test.ts (1)
packages/typescript/ai/src/tools/tool-definition.ts (1)
  • toolDefinition (187-227)
packages/typescript/ai/src/tools/tool-definition.ts (1)
packages/typescript/ai/src/types.ts (3)
  • Tool (328-434)
  • ToolOptions (75-77)
  • InferSchemaType (60-60)
🔇 Additional comments (35)
packages/typescript/ai/src/types.ts (3)

71-77: Well-designed ToolOptions interface.

The ToolOptions<TContext> interface provides a clean, extensible pattern for passing execution context to tools. Using an options object rather than a positional parameter makes this backward-compatible and allows for future additions without breaking changes.


424-427: Execute signature change aligns with context propagation.

The updated signature <TContext = unknown>(args, options: ToolOptions<TContext>) cleanly threads context through tool execution while remaining backward compatible since context is optional in ToolOptions.


596-618: Excellent documentation for the context property.

The context property on ChatOptions is well-documented with a practical example showing database access and user ID retrieval. This clearly communicates the intended use case for context-aware tools.

packages/typescript/ai/tests/tool-call-manager.test.ts (1)

124-127: Test expectation correctly updated for new execute signature.

The assertion now expects the second argument { context: undefined }, which accurately reflects the updated tool execution flow where context is always passed (as undefined when not provided).

packages/typescript/ai/tests/ai-chat.test.ts (7)

8-14: Import update aligns with new type usage.

Adding ToolOptions to the imports is necessary for the new context support tests.


461-464: Test expectation correctly reflects context propagation.

The updated assertion verifies that tool.execute receives the expected arguments including the options object with context: undefined when no context is provided.


571-574: Consistent update for streaming tool arguments test.


1504-1507: Approval flow test correctly updated.

The pending tool execution with approval now properly expects the context option.


2619-2622: Approval response extraction test correctly updated.


3020-3166: Comprehensive context propagation test.

This test effectively validates:

  1. Context is passed through to tool.execute
  2. Context properties (like db) are accessible within the tool
  3. Mock interactions work correctly with context

The test structure with a mock database is a good pattern for verifying context-aware behavior.


3168-3249: Good coverage for optional context scenario.

This test verifies backward compatibility by ensuring tools work correctly when no context is provided. The assertion { context: undefined } confirms the options object is still passed.

packages/typescript/ai/tests/tool-definition.test.ts (2)

1-1: Minor import reordering.

Import order change is a stylistic adjustment with no functional impact.


277-338: Well-structured context support test.

The test properly validates:

  1. Typed context interface (TestContext)
  2. Context propagation to execute function
  3. Mock verification for database calls
  4. Proper use of tool.server<TestContext>(executeFn) for type-safe context
packages/typescript/ai-client/src/types.ts (2)

134-136: TContext generic properly added to ChatClientOptions.

The generic parameter enables type-safe context in client-side chat options while defaulting to unknown for backward compatibility.


212-229: Clear documentation distinguishing client vs server context.

The JSDoc clearly explains that this context is for client-side tools only, and that server tools should receive their context from the server-side chat() function. This distinction helps prevent confusion about context boundaries.

examples/ts-react-chat/src/routes/api.tanchat.ts (1)

100-106: LGTM!

The serverContext scaffolding provides a clear extension point for adding server-side resources (db connections, user sessions) in the future. The context is correctly passed to the chat() function.

Also applies to: 122-122

packages/typescript/ai-client/tests/chat-client.test.ts (3)

1-12: LGTM!

Imports are correctly added for the new test dependencies: toolDefinition and z for creating test tools, and ToolOptions type for type annotations.


670-694: LGTM!

This test is important - it validates that context (which may contain non-serializable objects like localStorage) is correctly kept client-side only and not sent over the wire. This addresses the concern about serializing complex objects.


696-731: LGTM!

Good backward compatibility test - verifies that tools work correctly when no context is provided, with context: undefined passed to the execute function.

packages/typescript/ai/src/core/chat.ts (3)

19-19: LGTM!

The ToolOptions import and the new private field options are correctly typed using TParams['context'] to preserve the context type from the chat parameters.

Also applies to: 49-49


80-80: LGTM!

Context is correctly extracted from configuration params and stored for propagation to tool executions.


382-388: LGTM!

Context is consistently propagated through both tool execution paths (checkForPendingToolCalls and processToolCalls), ensuring all server-side tool executions receive the context.

Also applies to: 451-457

packages/typescript/ai-client/src/chat-client.ts (3)

22-25: LGTM!

The ChatClient class is now properly generic over TTools and TContext, enabling type-safe context propagation. The private options field correctly stores the context for tool execution.

Also applies to: 37-37


51-54: LGTM!

Constructor correctly initializes the context from options, matching the updated ChatClientOptions<TTools, TContext> interface.


148-150: LGTM!

Context is correctly passed to client tool execution as the second argument, following the ToolOptions interface pattern.

packages/typescript/ai/src/tools/tool-calls.ts (5)

7-7: LGTM!

The ToolOptions import and updated executeTools signature correctly add optional context support with a sensible default of {} for backward compatibility.

Also applies to: 122-125


156-159: LGTM!

Context is correctly propagated to tool execution within ToolCallManager.executeTools.


260-268: LGTM!

The executeToolCalls function signature is correctly updated with the options parameter and proper JSDoc documentation explaining its purpose.


399-401: LGTM!

Context is correctly passed to approved server tool execution, maintaining consistency across all execution paths.


464-466: LGTM!

Context propagation is complete for all server tool execution paths - normal execution, approved execution, and via ToolCallManager.

packages/typescript/ai/src/tools/tool-definition.ts (5)

2-8: LGTM!

The imports are correctly structured as type-only imports, and ToolOptions is properly imported to support the new context-aware execute signatures.


13-21: LGTM!

The phantom type __contextType pattern is a valid TypeScript technique for carrying type information without runtime overhead. The optional modifier is appropriate since this is purely for type inference.


26-44: LGTM!

The ClientTool interface correctly adds the TContext generic parameter and updates the execute signature to accept ToolOptions<TContext>. The phantom type pattern matches ServerTool.


60-62: LGTM!

The AnyClientTool type correctly adds the fourth generic parameter to match the updated ClientTool interface.


118-133: LGTM!

The method-level generic TContext allows callers to specify the context type when instantiating tools (e.g., tool.server<{userId: string}>(...)), providing type-safe access to options.context. This addresses the previous review feedback about using an options argument for scalability.

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.

3 participants