Skip to content

feat(sdk): implements SessionContext for SDK tool calls#18862

Merged
mbleigh merged 10 commits intomainfrom
sdk-02-session-context
Feb 13, 2026
Merged

feat(sdk): implements SessionContext for SDK tool calls#18862
mbleigh merged 10 commits intomainfrom
sdk-02-session-context

Conversation

@mbleigh
Copy link
Contributor

@mbleigh mbleigh commented Feb 12, 2026

Adds SessionContext and error handling.

@mbleigh mbleigh requested a review from a team as a code owner February 12, 2026 00:47
@gemini-cli
Copy link
Contributor

gemini-cli bot commented Feb 12, 2026

Hi there! Thank you for your contribution to Gemini CLI.

To improve our contribution process and better track changes, we now require all pull requests to be associated with an existing issue, as announced in our recent discussion and as detailed in our CONTRIBUTING.md.

This pull request is being closed because it is not currently linked to an issue. Once you have updated the description of this PR to link an issue (e.g., by adding Fixes #123 or Related to #123), it will be automatically reopened.

How to link an issue:
Add a keyword followed by the issue number (e.g., Fixes #123) in the description of your pull request. For more details on supported keywords and how linking works, please refer to the GitHub Documentation on linking pull requests to issues.

Thank you for your understanding and for being a part of our community!

@gemini-cli gemini-cli bot closed this Feb 12, 2026
@gemini-cli
Copy link
Contributor

gemini-cli bot commented Feb 12, 2026

Hi @mbleigh, thank you so much for your contribution to Gemini CLI! We really appreciate the time and effort you've put into this.

We're making some updates to our contribution process to improve how we track and review changes. Please take a moment to review our recent discussion post: Improving Our Contribution Process & Introducing New Guidelines.

Key Update: Starting January 26, 2026, the Gemini CLI project will require all pull requests to be associated with an existing issue. Any pull requests not linked to an issue by that date will be automatically closed.

Thank you for your understanding and for being a part of our community!

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @mbleigh, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the Gemini CLI SDK by introducing a robust SessionContext mechanism, enabling tools to interact with the environment in a controlled and contextual manner. It also refines error handling for tool calls, providing more granular control over how errors are communicated to the underlying model. These changes lay foundational groundwork for more sophisticated and interactive agent capabilities within the SDK, as detailed in the newly added design document.

Highlights

  • SessionContext Implementation: Introduced a SessionContext object that provides tools with access to session-specific information like sessionId, cwd, transcript, and utility interfaces for filesystem (fs) and shell (shell).
  • Enhanced Tool Error Handling: Implemented a new ModelVisibleError class and a sendErrorsToModel option within tool definitions, allowing developers to control which errors are reported back to the model and which cause the tool invocation to fail silently.
  • Filesystem and Shell Abstractions: Added SdkAgentFilesystem and SdkAgentShell classes, providing sandboxed and policy-aware access to file system operations and shell command execution for tools.
  • SDK Design Documentation: A comprehensive SDK_DESIGN.md document was added, outlining the architecture and capabilities of the Gemini CLI SDK, including examples for various features like custom tools, hooks, skills, and extensions.
  • New Example and Tests: Included a new example (session-context.ts) demonstrating the usage of the SessionContext within a tool, along with new unit and integration tests to validate tool execution and error handling.
Changelog
  • .prettierignore
    • Added a new ignore pattern for packages/sdk/test-data/*.json files.
  • packages/sdk/SDK_DESIGN.md
    • Added a new design document outlining the architecture and features of the Gemini CLI SDK.
  • packages/sdk/examples/session-context.ts
    • Added a new example demonstrating how to access and utilize the SessionContext within a custom tool.
  • packages/sdk/src/agent.ts
    • Imported Content, SdkAgentFilesystem, SdkAgentShell, and SessionContext types.
    • Updated GeminiCliAgentOptions to include recordResponses and fakeResponses.
    • Modified SdkTool instantiation to pass the agent instance.
    • Initialized SdkAgentFilesystem and SdkAgentShell instances within the agent's sendStream method.
    • Constructed and passed a SessionContext object to tool invocations.
    • Enhanced tool execution error handling to log errors and provide a generic error message to the model for non-ModelVisibleError exceptions.
  • packages/sdk/src/fs.ts
    • Added a new file defining the SdkAgentFilesystem class, which implements AgentFilesystem for controlled file read/write operations.
  • packages/sdk/src/index.ts
    • Added new exports for agent.js, tool.js, and types.js to the SDK's main entry point.
  • packages/sdk/src/shell.ts
    • Added a new file defining the SdkAgentShell class, which implements AgentShell for controlled shell command execution.
  • packages/sdk/src/tool.integration.test.ts
    • Added new integration tests for GeminiCliAgent to verify tool execution success and proper handling of ModelVisibleError and sendErrorsToModel.
  • packages/sdk/src/tool.test.ts
    • Added new unit tests for the tool() function and SdkTool execution, covering successful execution, standard error throwing, ModelVisibleError handling, and sendErrorsToModel functionality.
  • packages/sdk/src/tool.ts
    • Introduced ModelVisibleError class for errors intended to be visible to the model.
    • Updated ToolDefinition interface to include an optional sendErrorsToModel property.
    • Modified Tool interface and tool function to allow the action callback to receive an optional SessionContext.
    • Updated SdkToolInvocation constructor to accept SessionContext and sendErrorsToModel.
    • Modified SdkToolInvocation's execute method to conditionally catch and report errors based on ModelVisibleError or sendErrorsToModel.
    • Added createInvocationWithContext method to SdkTool to facilitate passing SessionContext.
  • packages/sdk/src/types.ts
    • Added a new file defining core interfaces: AgentFilesystem, AgentShellOptions, AgentShellResult, AgentShell, and SessionContext.
  • packages/sdk/test-data/tool-catchall-error.json
    • Added new test data for verifying tool error handling when sendErrorsToModel is true.
  • packages/sdk/test-data/tool-error-recovery.json
    • Added new test data for verifying tool error recovery after a ModelVisibleError.
  • packages/sdk/test-data/tool-success.json
    • Added new test data for verifying successful tool execution.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces SessionContext for SDK tool calls, providing tools with controlled access to session information, filesystem, and shell execution. While the implementation includes new modules (fs, shell, types), comprehensive tests, and an improved error handling mechanism with ModelVisibleError and sendErrorsToModel, a high-severity command injection vulnerability was identified in the SdkAgentShell.exec method. This method executes raw command strings, creating a significant risk if user-controllable input is used. Addressing this vulnerability is critical. Additionally, there is a high-severity suggestion to refine how tool errors are propagated to the model for correct response formatting.

@mbleigh mbleigh reopened this Feb 12, 2026
@gemini-cli gemini-cli bot added the status/need-issue Pull requests that need to have an associated issue. label Feb 12, 2026
- adds tests to SDK tools
- adds ModelVisibleError for SDK error handling
- adds sdk test-data to .prettierignore
@mbleigh mbleigh force-pushed the sdk-02-session-context branch from 83a93f0 to 46b7f07 Compare February 12, 2026 01:58
@mbleigh
Copy link
Contributor Author

mbleigh commented Feb 12, 2026

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

The pull request introduces SessionContext for SDK tool calls, enhancing the SDK's functionality by providing tools with access to session-specific information like sessionId, cwd, transcript, and interfaces for filesystem (fs) and shell (shell) operations. This change, however, significantly increases the attack surface, introducing a critical command injection vulnerability from passing LLM-generated arguments directly to shell commands (as highlighted by the rule on sanitizing user-provided file paths for file system operations), and a high-severity prompt injection vulnerability due to passing raw user input to the LLM without proper sanitization (as per the rule on avoiding user input in llmContent). While the PR also includes error handling for tool execution and new test files, these security risks need immediate attention. Other comments address markdown syntax, TypeScript type usage, and copyright years.

Comment on lines 148 to 155
const invocation =
tool instanceof SdkTool
? tool.createInvocationWithContext(
args as object,
this.config.getMessageBus(),
context,
)
: tool.build(args as object);
Copy link
Contributor

Choose a reason for hiding this comment

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

security-critical critical

The GeminiCliAgent processes tool calls from the LLM by passing the model-generated arguments (toolCall.args) directly to tool implementations via the SessionContext. This context now includes powerful methods like context.shell.exec() and context.fs.writeFile(). If a developer creates a tool that passes arguments from the LLM to these methods, it creates a command injection vulnerability. An attacker can craft a prompt that causes the LLM to call such a tool with malicious arguments, leading to arbitrary command execution on the host system. The code on lines 148-155 in agent.ts directly facilitates this insecure data flow from the LLM to the tool invocation.

References
  1. Sanitize user-provided file paths used in file system operations to prevent path traversal vulnerabilities.

@@ -0,0 +1,279 @@
# `Gemini CLI SDK`

# `Examples`
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The heading for 'Examples' should be a level 2 heading to maintain consistency with other sections like 'Implementation Guidance' and 'Notes'.

Suggested change
# `Examples`
## `Examples`

import { GeminiCliAgent } from "@google/gemini-cli-sdk";

const agent = new GeminiCliAgent({
instructions: "This is a static string instruction"; // this is valid
Copy link
Contributor

Choose a reason for hiding this comment

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

high

There's a syntax error here. A semicolon is used instead of a comma to separate the instructions properties.

Suggested change
instructions: "This is a static string instruction"; // this is valid
instructions: "This is a static string instruction", // this is valid

a: z.number().describe('first number to add'),
b: z.number().describe('second number to add'),
}),
}, (({a, b}) => ({result: a + b}),);
Copy link
Contributor

Choose a reason for hiding this comment

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

high

There's a syntax error here. A comma is missing after the closing parenthesis of the action function, and there's an extra comma at the end.

Suggested change
}, (({a, b}) => ({result: a + b}),);
}, (({a, b}) => ({result: a + b}));

## `Subagents`

```ts
import { GeminiCliAgent, subagent } from "@google/gemini-cli";
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The import path for subagent is incorrect. It should be from @google/gemini-cli-sdk.

Suggested change
import { GeminiCliAgent, subagent } from "@google/gemini-cli";
import { GeminiCliAgent, subagent } from "@google/gemini-cli-sdk";

@@ -0,0 +1,35 @@
/**
* @license
* Copyright 2026 Google LLC
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The copyright year is set to 2026, which is in the future. This should be updated to the current year.

Suggested change
* Copyright 2026 Google LLC
* Copyright 2024 Google LLC

@@ -0,0 +1,69 @@
/**
* @license
* Copyright 2026 Google LLC
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The copyright year is set to 2026, which is in the future. This should be updated to the current year.

Suggested change
* Copyright 2026 Google LLC
* Copyright 2024 Google LLC

@@ -0,0 +1,147 @@
/**
* @license
* Copyright 2026 Google LLC
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The copyright year is set to 2026, which is in the future. This should be updated to the current year.

Suggested change
* Copyright 2026 Google LLC
* Copyright 2024 Google LLC

@@ -0,0 +1,143 @@
/**
* @license
* Copyright 2026 Google LLC
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The copyright year is set to 2026, which is in the future. This should be updated to the current year.

Suggested change
* Copyright 2026 Google LLC
* Copyright 2024 Google LLC

@@ -0,0 +1,41 @@
/**
* @license
* Copyright 2026 Google LLC
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The copyright year is set to 2026, which is in the future. This should be updated to the current year.

Suggested change
* Copyright 2026 Google LLC
* Copyright 2024 Google LLC

@gemini-cli
Copy link
Contributor

gemini-cli bot commented Feb 12, 2026

Hi there! Thank you for your contribution to Gemini CLI.

To improve our contribution process and better track changes, we now require all pull requests to be associated with an existing issue, as announced in our recent discussion and as detailed in our CONTRIBUTING.md.

This pull request is being closed because it is not currently linked to an issue. Once you have updated the description of this PR to link an issue (e.g., by adding Fixes #123 or Related to #123), it will be automatically reopened.

How to link an issue:
Add a keyword followed by the issue number (e.g., Fixes #123) in the description of your pull request. For more details on supported keywords and how linking works, please refer to the GitHub Documentation on linking pull requests to issues.

Thank you for your understanding and for being a part of our community!

@gemini-cli gemini-cli bot closed this Feb 12, 2026
@mbleigh mbleigh reopened this Feb 12, 2026
Copy link
Collaborator

Choose a reason for hiding this comment

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

Should add an abort signal to the public method surfaces here.

@gemini-cli
Copy link
Contributor

gemini-cli bot commented Feb 13, 2026

Hi there! Thank you for your contribution to Gemini CLI.

To improve our contribution process and better track changes, we now require all pull requests to be associated with an existing issue, as announced in our recent discussion and as detailed in our CONTRIBUTING.md.

This pull request is being closed because it is not currently linked to an issue. Once you have updated the description of this PR to link an issue (e.g., by adding Fixes #123 or Related to #123), it will be automatically reopened.

How to link an issue:
Add a keyword followed by the issue number (e.g., Fixes #123) in the description of your pull request. For more details on supported keywords and how linking works, please refer to the GitHub Documentation on linking pull requests to issues.

Thank you for your understanding and for being a part of our community!

@gemini-cli gemini-cli bot closed this Feb 13, 2026
@mbleigh mbleigh reopened this Feb 13, 2026
Base automatically changed from sdk-01-bootstrap to main February 13, 2026 06:15
@mbleigh mbleigh requested a review from a team as a code owner February 13, 2026 06:15
@github-actions
Copy link

Size Change: -2 B (0%)

Total Size: 24.4 MB

ℹ️ View Unchanged
Filename Size Change
./bundle/gemini.js 24.4 MB -2 B (0%)
./bundle/sandbox-macos-permissive-open.sb 890 B 0 B
./bundle/sandbox-macos-permissive-proxied.sb 1.31 kB 0 B
./bundle/sandbox-macos-restrictive-open.sb 3.36 kB 0 B
./bundle/sandbox-macos-restrictive-proxied.sb 3.56 kB 0 B
./bundle/sandbox-macos-strict-open.sb 4.82 kB 0 B
./bundle/sandbox-macos-strict-proxied.sb 5.02 kB 0 B

compressed-size-action

@mbleigh mbleigh enabled auto-merge February 13, 2026 07:23
@mbleigh mbleigh added this pull request to the merge queue Feb 13, 2026
Merged via the queue into main with commit b61a123 Feb 13, 2026
26 of 27 checks passed
@mbleigh mbleigh deleted the sdk-02-session-context branch February 13, 2026 07:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status/need-issue Pull requests that need to have an associated issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants