Skip to content

Feat: Dynamic authentication handling in MCPToolset from Adk ReadonlyContext.state using Callback #1198

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
335 commits
Select commit Hold shift + click to select a range
a414d05
chore: Enhance a2a event converter
seanzhougoogle Jun 25, 2025
ff48e57
Merge branch 'main' into fix_graph
hangfei Jun 25, 2025
67640da
fix: converts litellm generate config err
simonwei97 Jun 26, 2025
30f6c11
fix: Adding detailed information on each metric evaluation
ankursharmas Jun 26, 2025
7adcc0f
fix: Update google_search_tool.py to support updated Gemini LIVE mode…
rayira Jun 26, 2025
76cceee
chore: Add a2a task result aggregator
seanzhougoogle Jun 26, 2025
843c3ee
chore: Add a2a agent executor
seanzhougoogle Jun 26, 2025
8e80a91
chore: Add enable_a2a option to adk command line
seanzhougoogle Jun 26, 2025
af9899c
chore: Add a2a log utils for formatting a2a reqeust/response logs
seanzhougoogle Jun 26, 2025
5a94096
chore: update adk web
wyf7107 Jun 26, 2025
ec56403
feat: Add A2A endpoints to fast api server when --a2a option is speci…
seanzhougoogle Jun 26, 2025
e806278
chore: updating CONTRIBUTING.md with missing extra
jackwotherspoon Jun 27, 2025
6fdb83c
fix: Lock LangGraph version to <= 0.4.10
hangfei Jun 27, 2025
b742dad
chore: Enhance part_converter module to only import sys when needed a…
seanzhougoogle Jun 27, 2025
f96f7b0
chore: Enhance a2a_agent_executor module to raise error with meaningf…
seanzhougoogle Jun 27, 2025
c80b5d1
chore: Adding PR commit check github workflow
hangfei Jun 27, 2025
42f0a9b
chore: Use context_id as session_id and construct temp user_id from c…
seanzhougoogle Jun 27, 2025
252419b
fix: Save output in state via output_key only when the event is autho…
seanzhougoogle Jun 27, 2025
8e32c98
fix: Support API-Key for MCP Tool authentication
seanzhougoogle Jun 27, 2025
8455649
feat: Add remote a2a agent
seanzhougoogle Jun 27, 2025
46eeb74
fix: raise ValueError when sessionId and userId are incorrect combina…
soundTricker Jun 27, 2025
06510cb
fix: treat SQLite database update time as UTC for session's last upda…
xuanyang15 Jun 27, 2025
2452b3c
feat: Enable A2A features as experimental
seanzhougoogle Jun 27, 2025
d79a824
chore: Add a basic a2a agent demo sample
seanzhougoogle Jun 27, 2025
d56d06a
chore: Add a human in the loop a2a agent demo sample
seanzhougoogle Jun 27, 2025
a6dfb43
chore: Add an a2a agent to demo oauth flow
seanzhougoogle Jun 27, 2025
891652b
feat: Support protected write in BigQuery `execute_sql` tool
google-genai-bot Jun 27, 2025
68d2331
docs: Update CONTRIBUTING.md
hangfei Jun 27, 2025
692919d
chore: refactor the ADK Triaging Agent to make the code easier to read
xuanyang15 Jun 27, 2025
0c6a610
docs: Add AGENTS.md to provide relevant project context for the Gemin…
google-genai-bot Jun 28, 2025
e6e209d
chore: Create an example for multi agent live streaming
hangfei Jun 30, 2025
a3ef8df
fix: Avoid pydantic.ValidationError when the model stream returns emp…
hangfei Jun 30, 2025
60324bc
chore: update adk web
Jun 30, 2025
68d5825
fix: Make sure each partial event has different timestamp
DeanChensj Jul 1, 2025
d5dc91c
feat: BaseEvalService declaration and surrounding data models
ankursharmas Jul 1, 2025
451977f
chore: Add util to build our llms.txt and llms-full.txt files
hangfei Jun 28, 2025
6094d42
Merge pull request #1709 from google:my-feature-branch-llmstxt
copybara-github Jul 1, 2025
bcb727e
fix: continue the action when `grep -L` returns exit status 1
wuliang229 Jul 1, 2025
5feb978
Fix: Handle unexpected 'parameters' argument in FunctionTool.run_async
google-labs-jules[bot] Jun 26, 2025
6910f3f
doc: Update README.md
hangfei Jul 2, 2025
ef4aef7
chore: Update the retry logic of create session polling
DeanChensj Jul 2, 2025
0b1facb
Merge pull request #1656 from google:fix-transfer-to-agent-parameters…
copybara-github Jul 2, 2025
8985a2f
chore: Add tenacity into project.toml
DeanChensj Jul 2, 2025
223c78c
Merge pull request #1744 from google:hangfei-patch-3
copybara-github Jul 2, 2025
70e687b
chore: Update ResponseEvaluator to use newer version of Eval SDK
ankursharmas Jul 2, 2025
d735d74
feat: Add Safety evaluator metric
ankursharmas Jul 2, 2025
26d6123
fix: scenario where a user can access another users events given the …
sindrigunnars Jun 25, 2025
f268358
Merge pull request #1644 from sindrigunnars:fix-issue-1641-database-s…
copybara-github Jul 2, 2025
2a3111b
chore: update agents.md to include versioning strategy
hangfei Jul 2, 2025
d7a376b
fix: Remove duplicate options from `adk deploy`
DeanChensj Jul 3, 2025
2d39f80
fix: Replace Event ID generation with UUID4 to prevent SQLite integri…
rahulsamant37 Jul 3, 2025
3c945f0
Merge branch 'main' into fix_graph
DavidSchmidt00 Jul 4, 2025
3b4db02
Merge pull request #1778 from rahulsamant37:fix/event-id-uuid4-collis…
copybara-github Jul 4, 2025
694ae67
feat: Add `custom_metadata` to VertexAiSessionService event handling
DeanChensj Jul 4, 2025
dd0d088
chore: Add docstring to clarify that inmemory service are not suitabl…
DeanChensj Jul 7, 2025
9adccd9
fix: Use inspect.signature() instead of typing.get_type_hints
hangfei Jul 7, 2025
39656d9
feat: Add adk project overview and architecture
hangfei Jul 7, 2025
41bc352
test: Add tests for live streaming configs
hangfei Jul 7, 2025
b7840bd
Merge branch 'main' into fix_graph
DavidSchmidt00 Jul 7, 2025
7218f5a
feat: expose credential service in readonly context
matino Jul 8, 2025
d8dbbe8
refactor: extract mcp client creation logic to a separate method
seanzhougoogle Jul 8, 2025
067f941
feat: Implement auto rater-based evaluator for responses
jcpagadora737 Jul 8, 2025
c02f34b
chore: Update gemini model to 2.0 for a2a samples
seanzhougoogle Jul 8, 2025
59c22a1
fix: Support project-based gemini model path to use enterprise_web_se…
anmourchen Jul 8, 2025
12c3167
feat: Allow user to edit agent files/directories and apply changes wi…
abchang123 Jul 8, 2025
72c752d
chore: update adk web
wyf7107 Jul 8, 2025
2e30b18
feat(lite_llm): add PDF support
marcellomaugeri Jul 9, 2025
bd1d3b9
feat: Create PR agent for ADK github repo
genquan9 Jul 9, 2025
0fa619b
chore(fix typo): correct typo AUTHLIB_AVIALABLE → AUTHLIB_AVAILABLE
hironow Jul 9, 2025
ef4bdd4
fix: Fix view eval case
abchang123 Jul 9, 2025
fdafdb3
feat: add agent.clone() method
wuliang229 Jul 9, 2025
fd86004
chore: Release 1.6.0
seanzhougoogle Jul 10, 2025
1127bfd
test: Adds test for streaming + function calls
hangfei Jul 10, 2025
a2b7441
chore: rename `session_factory` to `sql_session` for readability
xuanyang15 Jul 10, 2025
d88525c
fix: improve partial event handling and streaming aggregation
seanzhougoogle Jul 10, 2025
f49f5dd
feat: Make InMemoryMemoryService thread-safe
google-genai-bot Jul 10, 2025
6432843
docs: s/readony_context/readonly_context/g
bih Jul 10, 2025
fcff3e1
chore: update triage agent to assign the issue to owner after labelin…
xuanyang15 Jul 10, 2025
2fc6f88
chore: remove unused line for Client()
wuliang229 Jul 10, 2025
75f46ba
chore: create an initial prototype agent to answer Github discussion …
xuanyang15 Jul 10, 2025
8ebe82c
feat(config): add APIs for building config agents
wuliang229 Jul 10, 2025
b3dc49a
feat(config): support loading from YAML config in CLI
wuliang229 Jul 10, 2025
5d21e59
feat(config): add disallow_transfer_to_parent and disallow_transfer_t…
wuliang229 Jul 10, 2025
9249d63
feat(config): add configs for ParallelAgent and SequentialAgent
wuliang229 Jul 10, 2025
d1cf32e
feat(config): add ParallelAgent and SequentialAgent to the loader
wuliang229 Jul 10, 2025
4d37008
fix: Add support for code execution result and skip inline data in an…
google-genai-bot Jul 10, 2025
1012ff7
test: add the unit test for EnterpriseWebSearchTool
anmourchen Jul 11, 2025
79e2d5f
Update base_toolset.py
seanzhou1023 Jul 11, 2025
a917c89
Merge branch 'main' into patch-1
seanzhou1023 Jul 11, 2025
1787d89
feat: ADK Plugin Base Class
pwwpche Jul 11, 2025
c176764
feat: Implement PluginService for registering and executing plugins
pwwpche Jul 11, 2025
6493df3
feat: Integrating Plugin with ADK
pwwpche Jul 11, 2025
82cd7b4
Merge branch 'main' into patch-1
seanzhou1023 Jul 11, 2025
4b91616
feat: Add implementation of BaseEvalService that runs evals locally
ankursharmas Jul 11, 2025
9b637f9
feat: Add configure service account auth for google_api_tool_set
seanzhougoogle Jul 11, 2025
ca473bf
Merge pull request #120 from soundTricker:feature/80-sa-auth-for-goog…
copybara-github Jul 11, 2025
4dc1b49
Merge pull request #1875 from bih:patch-1
copybara-github Jul 11, 2025
675619d
Merge pull request #1866 from hironow:hironow/type-fix-for-static
copybara-github Jul 11, 2025
cb6e798
Merge branch 'main' into fix_graph
seanzhou1023 Jul 11, 2025
dee254f
auto format codes
seanzhougoogle Jul 11, 2025
0b11a7f
Merge pull request #1602 from DavidSchmidt00:fix_graph
copybara-github Jul 11, 2025
8da29ec
Merge branch 'main' into main
seanzhou1023 Jul 11, 2025
68a5be2
auto format the codes
seanzhougoogle Jul 11, 2025
84e2844
Merge pull request #1855 from marcellomaugeri:main
copybara-github Jul 11, 2025
427b08e
Update readonly_context.py
seanzhou1023 Jul 11, 2025
b4cfdc4
Update test_readonly_context.py
seanzhou1023 Jul 11, 2025
c69d5cc
Update agent_tool.py
seanzhou1023 Jul 11, 2025
fe25aec
Merge branch 'main' into expose_credential_service
seanzhou1023 Jul 11, 2025
26c8bec
Merge pull request #1829 from matino:expose_credential_service
copybara-github Jul 11, 2025
95144c5
chore: Update the README of a2a sample agent
seanzhougoogle Jul 11, 2025
92e4baa
fix: Return final task result in task artifact instead of status message
seanzhougoogle Jul 11, 2025
e8bd6c3
fix: Fix the long running function response event merge logic
seanzhougoogle Jul 11, 2025
18c0dfd
feat(config): support sub_agents in BaseAgentConfig
wuliang229 Jul 11, 2025
be590a3
feat(config): support `output_key` and `include_contents` in LlmAgent…
wuliang229 Jul 12, 2025
363e3b3
feat: Adding implementation of evaluate method in LocalEvalService
ankursharmas Jul 12, 2025
26eafb6
feat: Add support for persisting eval run results
ankursharmas Jul 12, 2025
f66ec6e
feat: Add a sample for how to use plugins
pwwpche Jul 13, 2025
b6e832a
fix: Import A2A well known path from A2A sdk
holtskinner Jul 14, 2025
340c57e
fix: Add instruction in long running tool description to avoid being …
seanzhougoogle Jul 14, 2025
9298f27
fix: Correct EventAction merging logic and add corresponding tests
iwknow Jul 13, 2025
aff819d
docs: Fix docstring and update module public name list for generating…
seanzhougoogle Jul 14, 2025
4638f73
feat: add testing endpoint for builder
wyf7107 Jul 14, 2025
f13c166
chore: update ADK Answering Agent to label the discussion with "bot_r…
xuanyang15 Jul 15, 2025
23786cb
docs: Update doc string for GcsArtifactService
seanzhougoogle Jul 15, 2025
7f9ad5b
fix: Process ListEvents response correctly when getSession is called
google-genai-bot Jul 15, 2025
1302b2f
feat: Implement in memory EvalSetsManager
ankursharmas Jul 15, 2025
c5bc8d1
fix: Use starred tuple unpacking on GCS artifact blob names for versi…
zshehov Jun 26, 2025
3476c33
Merge pull request #1955 from iwknow:func_fix
copybara-github Jul 15, 2025
c6e7790
refactor: Move list_artifacts from tool_context to callback_context
seanzhougoogle Jul 15, 2025
f6f4752
fix: Support project-based gemini model path for BuiltInCodeExecutor …
seanzhougoogle Jul 15, 2025
cf480ad
Merge pull request #1669 from zshehov:use-starred-tuple-unpacking-on-…
copybara-github Jul 15, 2025
ae6a9a6
feat(config): support built-in tools and referencing tools in code
wuliang229 Jul 15, 2025
e104c2e
fix: Don't set error_code and error_message when model stop response …
seanzhougoogle Jul 15, 2025
0c0213e
feat(config): support callbacks in BaseAgent and LlmAgent
wuliang229 Jul 15, 2025
d0dfee4
fix: return empty list in place of raising FileNotFoundError when the…
Poggecci Jul 15, 2025
86d4561
chore: adk Add more documentations for ADK live feature in ADK.md
hangfei Jul 15, 2025
b8ed635
fix: Create correct object for image and video content in litellm
seanzhougoogle Jul 15, 2025
65cea1b
refactor: Use CallbackContext in credential service for saving/loadin…
seanzhougoogle Jul 15, 2025
8fd4bdf
docs: Update agent transfer related doc string and comments
seanzhougoogle Jul 15, 2025
2967bae
refactor: Add save_credential and load_credential in callback context…
seanzhougoogle Jul 15, 2025
50f4391
feat: Add ability to send state change with message
abchang123 Jul 15, 2025
13d79d0
chore: update adk-web
wyf7107 Jul 16, 2025
3eac6e9
feat: Add ability to send state change with message
google-genai-bot Jul 16, 2025
03f67ae
ADK changes
google-genai-bot Jul 16, 2025
6a902d3
feat: Implement Activity Start and End signals in LiveRequestQueue an…
hangfei Jul 16, 2025
81bd329
feat: Add tool callback chaining support for live streaming
hangfei Jul 16, 2025
8ba1e1d
chore: Release 1.7.0
wyf7107 Jul 16, 2025
c2572e1
chore: Update label name for bot triaged issues
DeanChensj Jul 16, 2025
08d102b
fix: update documentation owner's Github username for the ADK Triage …
xuanyang15 Jul 17, 2025
b147c18
feat: Update builder/save endpoint to accept files as input. Write th…
Jul 17, 2025
9ddb642
fix: Set response schema for function that returns None
seanzhougoogle Jul 17, 2025
953d536
fix: Add response schema for agent tool function declaration even whe…
seanzhougoogle Jul 17, 2025
d94c14e
fix: Raise `NotFoundError` in `list_eval_sets` function when app_name…
ankursharmas Jul 17, 2025
b28c6e7
chore: add `to_session` method in `StorageSession` for readability
xuanyang15 Jul 17, 2025
75454a7
fix: use the same word extractor for query and event contents in InMe…
xuanyang15 Jul 17, 2025
79a6d7b
chore: remove the redundant `service.bucket` setting in `mock_gcs_art…
xuanyang15 Jul 17, 2025
2e402cf
chore: update ADK Triage Agent to set issue type
xuanyang15 Jul 17, 2025
a1dc926
fix(schema to dict): fix serialization of tools with nested schema
thiagosalvatore Jul 17, 2025
486605e
reformat file structure
thiagosalvatore Jul 17, 2025
9a4ff1b
Merge branch 'main' into main
thiagosalvatore Jul 17, 2025
fb4c6d5
add docstring
thiagosalvatore Jul 17, 2025
f22b74c
Merge branch 'main' of github.com:thiagosalvatore/adk-python
thiagosalvatore Jul 17, 2025
37032d0
fix: specify version into the uv installation action to bypass the se…
xuanyang15 Jul 17, 2025
3ffeacd
chore: add a script to upload ADK docs for the ADK Answering Agent
xuanyang15 Jul 17, 2025
fa0247b
feat: Enable FinalResponseMatchV2 metric as an experiment
ankursharmas Jul 17, 2025
a0224a1
feat: Support passing fully qualified agent engine resource name when…
DeanChensj Jul 17, 2025
acf3e25
chore: lint fixings in vertex_ai_memory_bank.py
Jacksunwei Jul 17, 2025
a8157e3
chore: fixes formatting in adk_project_overview_and_architecture.md
Jacksunwei Jul 18, 2025
6acdd47
Merge branch 'main' into fix/missing-path-level-parameters
hangfei Jul 18, 2025
651906d
fix: support path level parameters for open_api_spec_parser
seanzhougoogle Jul 18, 2025
b2ccef4
Merge branch 'main' into main
seanzhou1023 Jul 18, 2025
a5861d5
Merge pull request #2020 from thiagosalvatore:main
copybara-github Jul 18, 2025
91e782d
Merge pull request #547 from jeffreyrubi:fix/missing-path-level-param…
copybara-github Jul 18, 2025
0a598d7
chore: allow "from google.adk.tools import AgentTool"
wuliang229 Jul 18, 2025
09c599c
chore: remove pr-commit-check
hangfei Jul 18, 2025
95829b9
feat: Enhance LangchainTool to accept more forms of functions
hangfei Jul 18, 2025
28e2c0a
feat: History Management Sample
calvingiles Jul 19, 2025
9c9e38f
feat: Add support for vertex gemini model optimizer
calvingiles Jul 19, 2025
63555da
refactor: only import some module when needed and add follow_symlink=…
google-genai-bot Jul 19, 2025
1225976
chore: Autoformat history_management agent codes
seanzhougoogle Jul 20, 2025
2eff71f
feat: Allow toolset to process llm_request before tools returned by it
seanzhougoogle Jul 21, 2025
209788c
docs: Fix missing toolbox-core dependency and improve installation guide
designcomputer Jul 21, 2025
70b87f8
feat: make GCS artifact service async under the hood
condorcet Jul 21, 2025
c82f799
chore: Update the error message when A2A is not supported for the ins…
seanzhougoogle Jul 21, 2025
bf341ce
chore: Remove unused import from hello world sample agent
seanzhougoogle Jul 21, 2025
0499070
fix: add utf-8 encoding to file based reads and writes of eval data
ankursharmas Jul 21, 2025
18b49a2
fix: Check that `mean_score` is a valid float value
ankursharmas Jul 21, 2025
316949e
chore: undo the workaround which bypassed the setup-uv bug
xuanyang15 Jul 21, 2025
92d4715
fix: allows current sub-agent to finish execution before exiting the …
Jacksunwei Jul 21, 2025
853b966
feat(config): support input/output schema by fully-qualified code ref…
wuliang229 Jul 21, 2025
8b99e69
fix: Add buffer to the write file option
Jul 21, 2025
8bb0704
feat: Add agent card builder
seanzhougoogle Jul 21, 2025
1353e83
feat: Add camel case converter for agents
abchang123 Jul 21, 2025
09e187e
feat: Use LocalEvalService to run all evals in cli and web
ankursharmas Jul 21, 2025
b233e18
feat: Add an to_a2a util to convert adk agent to A2A ASGI application
seanzhougoogle Jul 21, 2025
d094f5c
chore: Add an a2a sample agent to demo running the a2a server via unv…
seanzhougoogle Jul 22, 2025
ecc5bae
feat: Add ComputerUseToolset
seanzhougoogle Jul 22, 2025
3f0c319
chore: follow-up #946 to allow session db kwargs in fast api entrance
Colstuwjx Jul 22, 2025
b3f909f
fix: Handle non-json-serializable values in the `execute_sql` tool
google-genai-bot Jul 22, 2025
61abb32
chore: Allow httpoptions override in VertexAiSessionService
DeanChensj Jul 22, 2025
0209735
fix(comment): fix comment to malicious user cannot obtain another use…
mthorme Jul 22, 2025
6988b4c
fix: Move some API request and responses to DEBUG logging level
ankursharmas Jul 22, 2025
b9b33fc
chore: update adk web
wyf7107 Jul 22, 2025
ee9f471
chore: Update docstring for is_final_response method
seanzhougoogle Jul 22, 2025
c56b18f
fix: ModuleNotFound error should be caught when dependencies of Local…
ankursharmas Jul 22, 2025
b9e9f74
feat: Refactor AgentLoader into base class and add InMemory impl alon…
Poggecci Jul 22, 2025
f709cf4
fix: Use correct type for actions parameter in ApplicationIntegration…
manifoldtimblin Jul 22, 2025
bdb2225
chore: Update a2a-sdk to 0.2.16
holtskinner Jul 23, 2025
e6676f9
chore: fix UT failures of test_google_llm.py
seanzhougoogle Jul 23, 2025
6b9cf3a
chore: Fixed flaky test_update_credential_with_tokens unittest
seanzhougoogle Jul 23, 2025
400312b
chore: Replace imports by importing from actual module instead of fro…
seanzhougoogle Jul 23, 2025
d8c9b33
feat: Refactored AgentEvaluator and updated it to use LocalEvalService
ankursharmas Jul 23, 2025
ccceb13
fix: add space to allow adk deploy cloud_run --a2a
andrewlarimer Jul 23, 2025
52322ab
chore: Release 1.8.0
ankursharmas Jul 23, 2025
ea55e0f
feat: Add camel case converter for agents
abchang123 Jul 23, 2025
0d8f0e6
feat: modularize fast_api.py to allow simpler construction of API Server
Poggecci Jul 23, 2025
918e603
feat: add new callbacks to handle tool and model errors
pwwpche Jul 23, 2025
9866a8b
feat: Add sample plugin for logging
pwwpche Jul 23, 2025
81a555a
feat: Expose Gemini RetryOptions to client
pwwpche Jul 23, 2025
6b181a5
feat: add support for session resumption(only transparent mode) confi…
hangfei Jul 24, 2025
66e9535
feat: modularize fast_api.py to allow simpler construction of API Server
google-genai-bot Jul 24, 2025
fbc4b8f
fix: Add absolutize_imports option when deploying to agent engine
yeesian Jul 24, 2025
8bdd39d
fix: eval module not found exception string
kavinkumar807 Jul 24, 2025
5e04d15
feat: modularize fast_api.py to allow simpler construction of API Server
Poggecci Jul 24, 2025
114bf05
feat: add `-v`, `--verbose` flag to enable DEBUG logging as a shortcu…
xuanyang15 Jul 24, 2025
709cae9
feat: Add a CLI option to update an agent engine instance
yeesian Jul 24, 2025
fc24b30
chore: Filter event with only functions, thought_signatures when addi…
DeanChensj Jul 24, 2025
0300929
fix: Fix incorrect token count mapping in telemetry
tl-nguyen Jul 24, 2025
3c939d5
feat: cli funcionality to deploy an Agent to a running GKE cluster
vicentefb Jul 24, 2025
76df3d1
fix: Fix unsafe_local_code_executor for import scope
qieqieplus Jul 25, 2025
2ae6c1c
feat(config): Adds CustomAgentConfig to support user-defined agents i…
Jacksunwei Jul 25, 2025
474aea4
chore: experiment endpoint
wyf7107 Jul 25, 2025
7f46154
fix: Switch from agent_engine_name to agent_engine_id for updating in…
yeesian Jul 25, 2025
81aad8a
chore(config): Moves agent configs to separate python files
Jacksunwei Jul 25, 2025
e9e7996
feat: Added an Fast API new endpoint to serve eval metric info
ankursharmas Jul 25, 2025
50d41ce
feat(config): support ADK built-in and custom tools in config
wuliang229 Jul 27, 2025
97b64ab
Merge branch 'main' of https://github.com/google/adk-python into stdi…
pandasanjay Jul 28, 2025
177377d
Merge branch 'main' into stdio_mcp_passing_env_from_adk_state
pandasanjay Jul 28, 2025
63ec4fd
Formated and Unittest fix
pandasanjay Jul 28, 2025
8acf960
Merge branch 'stdio_mcp_passing_env_from_adk_state' of https://github…
pandasanjay Jul 28, 2025
0aa070b
Update tests/unittests/tools/mcp_tool/test_mcp_toolset_auth.py
pandasanjay Jul 28, 2025
55acf83
Update src/google/adk/tools/mcp_tool/mcp_toolset.py
pandasanjay Jul 28, 2025
b048e40
Copilot sugession
pandasanjay Jul 28, 2025
985cc2d
Update src/google/adk/tools/mcp_tool/mcp_session_manager.py
pandasanjay Jul 28, 2025
255db3d
Update tests/unittests/tools/mcp_tool/test_mcp_toolset_auth.py
pandasanjay Jul 28, 2025
7bc83e5
Update src/google/adk/tools/mcp_tool/mcp_toolset.py
pandasanjay Jul 28, 2025
025a965
Copilot sugession
pandasanjay Jul 28, 2025
32ee080
Merge branch 'stdio_mcp_passing_env_from_adk_state' of https://github…
pandasanjay Jul 28, 2025
425794e
Merge branch 'main' of https://github.com/google/adk-python into stdi…
pandasanjay Jul 28, 2025
e9ae377
chore: fix the ci
pandasanjay Jul 28, 2025
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
80 changes: 80 additions & 0 deletions contributing/samples/mcp_stdio_user_auth_passing_sample/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Sample: Passing User Token from Agent State to MCP via ContextToEnvMapperCallback

This sample demonstrates how to use the `context_to_env_mapper_callback` feature in ADK to pass a user token from the agent's session state to an MCP process (using stdio transport). This is useful when your MCP server (built by your organization) requires the same user token for internal API calls.

## How it works
- The agent is initialized with a `MCPToolset` using `StdioServerParameters`.
- The `context_to_env_mapper_callback` is set to a function that extracts the `user_token` from the agent's state and maps it to the `USER_TOKEN` environment variable.
- When the agent calls the MCP, the token is injected into the MCP process environment, allowing the MCP to use it for internal authentication.

## Directory Structure
```
contributing/samples/stdio_mcp_user_auth_passing_sample/
Copy link
Preview

Copilot AI Jul 28, 2025

Choose a reason for hiding this comment

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

The directory path in the documentation doesn't match the actual directory name 'mcp_stdio_user_auth_passing_sample'. It should be 'mcp_stdio_user_auth_passing_sample/'.

Suggested change
contributing/samples/stdio_mcp_user_auth_passing_sample/
contributing/samples/mcp_stdio_user_auth_passing_sample/

Copilot uses AI. Check for mistakes.

├── agent.py # Basic agent setup
├── main.py # Complete runnable example
└── README.md
```

## How to Run

### Option 1: Run the complete example
```bash
cd /home/sanjay-dev/Workspace/adk-python
python -m contributing.samples.stdio_mcp_user_auth_passing_sample.main
Copy link
Preview

Copilot AI Jul 28, 2025

Choose a reason for hiding this comment

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

The module path in the command doesn't match the actual directory name 'mcp_stdio_user_auth_passing_sample'. It should be 'mcp_stdio_user_auth_passing_sample.main'.

Suggested change
python -m contributing.samples.stdio_mcp_user_auth_passing_sample.main
python -m contributing.samples.mcp_stdio_user_auth_passing_sample.main

Copilot uses AI. Check for mistakes.

```

### Option 2: Use the agent in your own code
```python
from contributing.samples.stdio_mcp_user_auth_passing_sample.agent import create_agent
from google.adk.sessions import Session

agent = create_agent()
session = Session(
id="your_session_id",
app_name="your_app_name",
user_id="your_user_id"
)

# Set user token in session state
session.state['user_token'] = 'YOUR_ACTUAL_TOKEN_HERE'
session.state['api_endpoint'] = 'https://your-internal-api.com'

# Then use the agent in your workflow...
```

## Flow Diagram

```mermaid
graph TD
subgraph "User Application"
U[User]
end

subgraph "Agent Process"
A[Agent Instance<br/>per user-app-agentid]
S[Session State<br/>user_token, api_endpoint]
C[ContextToEnvMapperCallback]
end

subgraph "MCP Process"
M[MCP Server<br/>stdio transport]
E[Environment Variables<br/>USER_TOKEN, API_ENDPOINT]
API[Internal API Calls]
end

U -->|Sends request| A
A -->|Reads state| S
S -->|Extracts tokens| C
C -->|Maps to env vars| E
A -->|Spawns with env| M
M -->|Uses env vars| API
API -->|Response| M
M -->|Tool result| A
A -->|Response| U
```

## Context
- Each agent instance is initiated per user-app-agentid.
- The agent receives a user context (with token) and calls the MCP using stdio transport.
- The MCP, built by the same organization, uses the token for internal API calls.
- The ADK's context-to-env mapping feature makes this seamless.
Empty file.
60 changes: 60 additions & 0 deletions contributing/samples/mcp_stdio_user_auth_passing_sample/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"""
Sample: Using ContextToEnvMapperCallback to pass user token from agent state to MCP via stdio transport.
"""

import os
import tempfile
from typing import Any
from typing import Dict

from google.adk.agents.llm_agent import LlmAgent
from google.adk.tools.mcp_tool.mcp_session_manager import StdioConnectionParams
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset
from mcp import StdioServerParameters

_allowed_path = os.path.dirname(os.path.abspath(__file__))


def user_token_env_mapper(state: Dict[str, Any]) -> Dict[str, str]:
"""Extracts USER_TOKEN from agent state and maps to MCP env."""
env = {}
if "user_token" in state:
env["USER_TOKEN"] = state["user_token"]
if "api_endpoint" in state:
env["API_ENDPOINT"] = state["api_endpoint"]

print(f"Environment variables being passed to MCP: {env}")
return env


def create_agent() -> LlmAgent:
"""Create the agent with context to env mapper callback."""
# Create a temporary directory for the filesystem server
temp_dir = tempfile.mkdtemp()

return LlmAgent(
model="gemini-2.0-flash",
name="user_token_agent",
instruction=f"""
You are an agent that calls an internal MCP server which requires a user token for internal API calls.
The user token is available in your session state and must be passed to the MCP process as an environment variable.
Test directory: {temp_dir}
""",
tools=[
MCPToolset(
connection_params=StdioConnectionParams(
server_params=StdioServerParameters(
command="npx",
args=[
"-y", # Arguments for the command
"@modelcontextprotocol/server-filesystem",
_allowed_path,
],
),
timeout=5,
),
get_env_from_context_fn=user_token_env_mapper,
tool_filter=["read_file", "list_directory"],
)
],
)
95 changes: 95 additions & 0 deletions contributing/samples/mcp_stdio_user_auth_passing_sample/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
"""
Sample: Using ContextToEnvMapperCallback to pass user token from agent state to MCP via stdio transport.
"""

import asyncio

from google.adk.agents.invocation_context import InvocationContext
from google.adk.agents.readonly_context import ReadonlyContext
from google.adk.sessions import InMemorySessionService
from google.adk.sessions import Session

from .agent import create_agent


async def main():
"""Example of how to set up and run the agent with user token."""
print("=== STDIO MCP User Auth Passing Sample ===")
print()

# Create the agent
agent = create_agent()
print(f"✓ Created agent: {agent.name}")

# Create session service and session
session_service = InMemorySessionService()
session = Session(
id="sample_session",
app_name="stdio_mcp_user_auth_passing_sample",
user_id="sample_user",
)
print(f"✓ Created session: {session.id}")

# Set user token in session state
session.state["user_token"] = "sample_user_token_123"
session.state["api_endpoint"] = "https://internal-api.company.com"
print(f"✓ Set session state with user_token: {session.state['user_token']}")

# Create invocation context
invocation_context = InvocationContext(
invocation_id="sample_invocation",
agent=agent,
session=session,
session_service=session_service,
)

# Create readonly context
readonly_context = ReadonlyContext(invocation_context)
print(f"✓ Created readonly context")

print()
print("=== Demonstrating User Auth Token Passing to MCP ===")
print(
"Note: This sample shows how the callback extracts environment variables."
)
print("In a real scenario, these would be passed to an actual MCP server.")
print()

# Access the MCP toolset to demonstrate the callback
mcp_toolset = agent.tools[0]
mcp_session_manager = mcp_toolset._mcp_session_manager

# Extract environment variables using the callback (without connecting to MCP)
if mcp_session_manager._context_to_env_mapper_callback:
print("✓ Context-to-env mapper callback is configured")

# Simulate what happens during MCP session creation
env_vars = mcp_session_manager._extract_env_from_context(readonly_context)

print(f"✓ Extracted environment variables:")
for key, value in env_vars.items():
print(f" {key}={value}")
print()

print(
"✓ These environment variables would be injected into the MCP process"
)
print("✓ The MCP server can then use them for internal API calls")
else:
print("✗ No context-to-env mapper callback configured")

print()
print("=== Sample completed successfully! ===")
print()
print("Key points demonstrated:")
print("1. Session state holds user tokens and configuration")
print(
"2. Context-to-env mapper callback extracts these as environment"
" variables"
)
print("3. Environment variables would be passed to MCP server processes")
print("4. MCP servers can use these for authenticated API calls")


if __name__ == "__main__":
asyncio.run(main())
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ dependencies = [
"google-cloud-storage>=2.18.0, <3.0.0", # For GCS Artifact service
"google-genai>=1.21.1", # Google GenAI SDK
"graphviz>=0.20.2", # Graphviz for graph rendering
"mcp>=1.8.0;python_version>='3.10'", # For MCP Toolset
"mcp>=1.9.4;python_version>='3.10'", # For MCP Toolset
"opentelemetry-api>=1.31.0", # OpenTelemetry
"opentelemetry-exporter-gcp-trace>=1.9.0",
"opentelemetry-sdk>=1.31.0",
Expand Down
35 changes: 33 additions & 2 deletions src/google/adk/tools/mcp_tool/mcp_session_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import logging
import sys
from typing import Any
from typing import Callable
from typing import Dict
from typing import Optional
from typing import TextIO
Expand Down Expand Up @@ -177,13 +178,43 @@ def __init__(
else:
self._connection_params = connection_params
self._errlog = errlog

# Session pool: maps session keys to (session, exit_stack) tuples
self._sessions: Dict[str, tuple[ClientSession, AsyncExitStack]] = {}

# Lock to prevent race conditions in session creation
self._session_lock = asyncio.Lock()

def update_connection_params(
self,
new_connection_params: Union[
StdioServerParameters,
StdioConnectionParams,
SseConnectionParams,
StreamableHTTPConnectionParams,
],
) -> None:
"""Updates the connection parameters and invalidates existing sessions.

Args:
new_connection_params: New connection parameters to use.
"""
if isinstance(new_connection_params, StdioServerParameters):
logger.warning(
'StdioServerParameters is not recommended. Please use'
' StdioConnectionParams.'
)
self._connection_params = StdioConnectionParams(
server_params=new_connection_params,
timeout=5,
)
else:
self._connection_params = new_connection_params

# Clear existing sessions since connection params changed
# Sessions will be recreated on next request
Copy link
Preview

Copilot AI Jul 28, 2025

Choose a reason for hiding this comment

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

The comment mentions clearing sessions but the actual implementation doesn't clear the sessions dictionary. This could lead to stale sessions being reused with outdated connection parameters.

Suggested change
# Sessions will be recreated on next request
# Sessions will be recreated on next request
self._sessions.clear()

Copilot uses AI. Check for mistakes.

# Note: We don't close sessions here to avoid blocking,
# they will be cleaned up when detected as disconnected


def _generate_session_key(
self, merged_headers: Optional[Dict[str, str]] = None
) -> str:
Expand Down
Loading