Skip to content

[BUG] Direct tool calls for tools w/ context=True cause KeyError #1210

@q-maze

Description

@q-maze

Checks

  • I have updated to the lastest minor and patch version of Strands
  • I have checked the documentation and this is not expected behavior
  • I have searched ./issues and there are no duplicates of my issue

Strands Version

1.17.0

Python Version

3.13.4

Operating System

macOS 15.7

Installation Method

pip

Steps to Reproduce

from strands import Agent, ToolContext, tool

@tool(context=True)
def add_w_state(a: int, b:int, tool_context: ToolContext) -> int:
    result = a + b
    tool_context.agent.state.set("last_add_result", result)
    return result


def main():
    agent = Agent(tools=[add_w_state])
    agent.tool.add_w_state(a=1, b=1)
    print(agent.messages)


if __name__ == "__main__":
    main()

Expected Behavior

Direct method calls for tools with context should not cause an error.

[{'content': [{'text': 'agent.tool. add_w_state direct tool call.\n'
                       'Input parameters: {"a": 1, "b": 1}\n'}],
  'role': 'user'},
 {'content': [{'toolUse': {'input': {'a': 1, 'b': 1},
                           'name': 'add_w_state',
                           'toolUseId': 'tooluse_add_w_state_975207425'}}],
  'role': 'assistant'},
 {'content': [{'toolResult': {'content': [{'text': '2'}],
                              'status': 'success',
                              'toolUseId': 'tooluse_add_w_state_975207425'}}],
  'role': 'user'},
 {'content': [{'text': 'agent.tool. add_w_state was called.'}], 'role': 'assistant'}]

Actual Behavior

Direct method calls for tools with context causes an error.

[{'content': [{'text': 'agent.tool.add_w_state direct tool call.\n'
                       'Input parameters: {"a": 1, "b": 1}\n'}],
  'role': 'user'},
 {'content': [{'toolUse': {'input': {'a': 1, 'b': 1},
                           'name': 'add_w_state',
                           'toolUseId': 'tooluse_add_w_state_975207425'}}],
  'role': 'assistant'},
 {'content': [{'toolResult': {'content': [{'text': "Error: KeyError - 'agent'"}],
                              'status': 'error',
                              'toolUseId': 'tooluse_add_w_state_975207425'}}],
  'role': 'user'},
 {'content': [{'text': 'agent.tool.add_w_state was called.'}], 'role': 'assistant'}]

Additional Context

I am using a custom model object to utilize models from Snowflake Cortex.

Possible Solution

Add agent to invocation state dictionary on line 79 of strands.tools.executors._executor.

Related Issues

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions