diff --git a/benchmarks/bigquerybench/README.md b/benchmarks/bigquerybench/README.md new file mode 100644 index 0000000000..c10dcc8ab4 --- /dev/null +++ b/benchmarks/bigquerybench/README.md @@ -0,0 +1,337 @@ +# BigQueryBench: Skill Invocation & Instruction Adherence Evaluation + +## Overview + +BigQueryBench evaluates agents built with ADK's `SkillToolset` on +two dimensions: + +1. **Skill invocation correctness** (trace-based) — Did the agent + call the right skill tools with the right arguments? +2. **Instruction adherence** (LLM-as-judge) — Did the agent follow + the skill's instructions and produce correct results? + +The trace-based checks are deterministic. The instruction adherence +checks use natural-language rubrics evaluated by a judge LLM, making +them easy to write and immune to exact-wording variance. + +## Quick Start + +```bash +# Skill-only mode (no BigQuery credentials needed): +export GOOGLE_CLOUD_API_KEY=your-vertex-ai-api-key + +# Full mode (BigQuery + skills — requires ADC + project): +export GOOGLE_CLOUD_PROJECT=your-project-id +export GOOGLE_CLOUD_API_KEY=your-vertex-ai-api-key + +# Run all eval cases +python -m benchmarks.bigquerybench.runner + +# Run one case +python -m benchmarks.bigquerybench.runner --filter skill_load + +# Dry-run (validate JSON only, no LLM calls) +python -m benchmarks.bigquerybench.runner --dry-run + +# Run unit tests (no API keys needed) +pytest tests/unittests/benchmarks/bigquerybench/ -v +``` + +## How It Works + +``` +eval_sets/bigquerybench_eval.json + ↓ (user query + expected tool_uses + rubrics) +runner.py + ↓ runs agent via ADK Runner + ↓ collects event trace → Invocations +metrics.py + ├── tool_invocation_score: expected skill tool names ⊆ actual? + ├── tool_args_score: expected (tool, skill-arg) pairs ⊆ actual? + └── instruction_adherence_score: LLM judge checks rubrics + ↓ +PASS if all three scores meet thresholds +``` + +## Three Metrics + +| Metric | Type | What It Checks | Pass Condition | +|--------|------|----------------|----------------| +| `tool_invocation_score` | Trace | Correct skill tools called | Score = 1.0 | +| `tool_args_score` | Trace | Correct skill/resource/script targeted | Score = 1.0 | +| `instruction_adherence_score` | LLM judge | Agent followed instructions, output correct | Score >= 0.75 | + +A case **passes** when all three metrics meet their thresholds. + +## Eval Case Format + +Each eval case has three parts: +1. **`conversation`** — user query + expected skill tool calls +2. **`rubrics`** — natural-language assertions checked by the judge + +```json +{ + "eval_id": "skill_load_reference", + "conversation": [ + { + "invocation_id": "inv-01", + "user_content": { + "parts": [{"text": "Load the public datasets reference from bq-sql-analyst."}], + "role": "user" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}}, + {"name": "load_skill_resource", "args": { + "skill_name": "bq-sql-analyst", + "path": "references/public-datasets.md" + }} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "rubrics": [ + { + "rubric_id": "shows_datasets", + "rubric_content": { + "text_property": "The response contains information about BigQuery public datasets." + } + }, + { + "rubric_id": "loaded_skill_first", + "rubric_content": { + "text_property": "The agent loaded the skill instructions before loading the resource." + } + } + ], + "creation_timestamp": 0.0 +} +``` + +### Trace Checks (deterministic) + +| Field in `args` | Checked? | Why | +|-----------------|----------|-----| +| `name` | Yes | Must load the right skill (`load_skill`) | +| `skill_name` | Yes | Must target the right skill (`load_skill_resource`, `run_skill_script`) | +| `path` | Yes | Must load the right resource (`load_skill_resource`) | +| `script_path` | Yes | Must run the right script (`run_skill_script`) | + +### Rubrics (LLM-as-judge) + +Each rubric is a natural-language assertion about the agent's behavior +or output. The judge LLM reads the conversation (user request + tool +trace + final response) and answers yes/no per rubric. + +**Example rubrics:** +```json +{"rubric_id": "r1", "rubric_content": {"text_property": "The agent used AI.classify to classify the data."}} +{"rubric_id": "r2", "rubric_content": {"text_property": "The result contains a markdown table with group statistics."}} +{"rubric_id": "r3", "rubric_content": {"text_property": "The agent loaded the skill before running the script."}} +``` + +## Included Eval Cases + +| eval_id | Expected Trace | Rubrics | +|---------|---------------|---------| +| `skill_list_skills` | `list_skills()` | Lists bq-sql-analyst; includes description | +| `skill_load_sql_analyst` | `load_skill(name=bq-sql-analyst)` | Describes capabilities; mentions scripts | +| `skill_load_reference` | `load_skill` → `load_skill_resource` | Shows datasets; loaded skill first | +| `skill_query_with_reference` | `load_skill` → `load_skill_resource` | Consulted reference; summarizes datasets; followed workflow | +| `skill_run_format_script` | `load_skill` → `run_skill_script` | Loaded before run; has table; has columns | + +## Example Output + +``` +======================================================================== + BigQueryBench — Skill Evaluation +======================================================================== + +[1/5] skill_list_skills + -> list_skills() + tools=1.00 args=1.00 adherence=1.00 PASS + +[2/5] skill_load_sql_analyst + -> load_skill(name='bq-sql-analyst') + tools=1.00 args=1.00 adherence=1.00 PASS + +[3/5] skill_load_reference + -> load_skill(name='bq-sql-analyst') + -> load_skill_resource(skill_name='bq-sql-analyst', path='references/public-datasets.md') + tools=1.00 args=1.00 adherence=1.00 PASS + +[4/5] skill_query_with_reference + -> load_skill(name='bq-sql-analyst') + -> load_skill_resource(skill_name='bq-sql-analyst', path='references/public-datasets.md') + tools=1.00 args=1.00 adherence=1.00 PASS + +[5/5] skill_run_format_script + -> load_skill(name='bq-sql-analyst') + -> run_skill_script(skill_name='bq-sql-analyst', script_path='scripts/format_results.py') + tools=1.00 args=1.00 adherence=1.00 PASS + +Eval Case Tools Args Adhere Result +------------------------------------------------------------------------ +skill_list_skills 1.00 1.00 1.00 PASS +skill_load_sql_analyst 1.00 1.00 1.00 PASS +skill_load_reference 1.00 1.00 1.00 PASS +skill_query_with_reference 1.00 1.00 1.00 PASS +skill_run_format_script 1.00 1.00 1.00 PASS +------------------------------------------------------------------------ + +======================================================================== + Summary +======================================================================== + Cases: 5/5 (100.0%) + Avg Tool Match: 1.00 + Avg Args Match: 1.00 + Avg Adherence: 1.00 + Elapsed: 488.8s +======================================================================== +``` + +## Adding a New Eval Case + +### For an existing skill + +Add a JSON object to `bigquerybench_eval.json` with both `tool_uses` +(trace expectations) and `rubrics` (instruction adherence assertions). + +```json +{ + "eval_id": "skill_explore_usa_names", + "conversation": [ + { + "invocation_id": "inv-new-01", + "user_content": { + "parts": [{"text": "Use the bq-sql-analyst skill to explore the usa_names dataset."}], + "role": "user" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}}, + {"name": "load_skill_resource", "args": {"skill_name": "bq-sql-analyst", "path": "references/public-datasets.md"}} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "rubrics": [ + { + "rubric_id": "consulted_ref", + "rubric_content": {"text_property": "The agent consulted the public datasets reference."} + }, + { + "rubric_id": "mentions_usa_names", + "rubric_content": {"text_property": "The response mentions the usa_names dataset and its columns."} + } + ], + "creation_timestamp": 0.0 +} +``` + +### For a new skill + +1. Create a skill directory under `skills/`: + ``` + skills/my-new-skill/ + ├── SKILL.md + ├── references/ + └── scripts/ + ``` + +2. Register it in `agent.py`: + ```python + _SKILL_NAMES = [ + "bq-sql-analyst", + "my-new-skill", # ← add here + ] + ``` + +3. Add eval cases with trace expectations + rubrics. + +### Writing Good Rubrics + +**Do:** +- Assert observable behavior: "The agent loaded the skill before running the script." +- Assert output properties: "The response contains a table with columns name and count." +- Assert domain correctness: "The result includes the top 3 Shakespeare works." + +**Don't:** +- Assert exact wording: "The response starts with 'Here are the results'." +- Assert implementation details: "The agent called execute_sql with SELECT DISTINCT." +- Use vague assertions: "The response is good." + +### When Do You Need Code Changes? + +| Scenario | JSON | `metrics.py` | `runner.py` | `agent.py` | +|----------|:----:|:------------:|:-----------:|:----------:| +| New eval case, existing skill | Yes | - | - | - | +| New skill added to `skills/` | Yes | - | - | Yes (add to `_SKILL_NAMES`) | +| Change judge model or threshold | - | Yes | - | - | +| Need entirely new metric | Yes | Yes | Yes | - | +| Agent instruction change | - | - | - | Yes | + +## Architecture + +``` +benchmarks/bigquerybench/ +├── __init__.py +├── agent.py # LlmAgent + BigQueryToolset + SkillToolset +├── runner.py # Runs agent, scores trace + rubrics +├── metrics.py # 3 metrics: trace (x2) + LLM-as-judge (x1) +├── eval_sets/ +│ └── bigquerybench_eval.json # 5 eval cases with rubrics +└── skills/ + └── bq-sql-analyst/ + ├── SKILL.md + ├── references/ + │ └── public-datasets.md + └── scripts/ + └── format_results.py + +tests/unittests/benchmarks/bigquerybench/ +└── test_metrics.py # 14 tests (trace + LLM judge + JSON validation) +``` + +## Retry Backoff + +Both the agent model and the LLM judge use exponential backoff with +retry on 429 (rate limit) errors: + +- **Agent model**: 5 attempts, 2s initial delay, 2x exponential + backoff (via `HttpRetryOptions`) +- **LLM judge**: 5 attempts, 2s → 4s → 8s → 16s manual backoff, + plus 3 HTTP-level retries per attempt + +## Environment Variables + +| Variable | Required | Description | +|----------|----------|-------------| +| `GOOGLE_CLOUD_API_KEY` | Yes | Vertex AI API key for agent model + judge | +| `GOOGLE_CLOUD_PROJECT` | No | GCP project for BigQuery API (enables BigQuery toolset) | +| `BQ_EVAL_WRITE_MODE` | No | `blocked` (default) / `protected` / `allowed` | + +**Two modes:** +- **Skill-only** (default): Set `GOOGLE_CLOUD_API_KEY` only. + BigQuery toolset is skipped; all 5 skill eval cases run. +- **Full mode**: Set both `GOOGLE_CLOUD_API_KEY` and + `GOOGLE_CLOUD_PROJECT` (+ ADC configured). BigQuery toolset + is enabled alongside skills. + +## Troubleshooting + +| Symptom | Fix | +|---------|-----| +| `tool_invocation_score = 0` | Agent didn't call expected skill tool — check agent instructions | +| `tool_args_score < 1.0` | Agent targeted wrong skill or resource — check user query specificity | +| `adherence < 0.75` | Agent produced wrong output — review rubrics and skill instructions | +| 429 RESOURCE_EXHAUSTED | Rate limit — retry backoff handles this automatically; wait and retry | +| Skill not found | Verify skill dir exists in `skills/` and name is in `_SKILL_NAMES` in `agent.py` | +| Judge LLM fails | Check `GOOGLE_CLOUD_API_KEY` is set correctly | +| `load_skill_resource` fails | Check the `path` arg matches a real file under the skill dir | diff --git a/benchmarks/bigquerybench/__init__.py b/benchmarks/bigquerybench/__init__.py new file mode 100644 index 0000000000..58d482ea38 --- /dev/null +++ b/benchmarks/bigquerybench/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/benchmarks/bigquerybench/agent.py b/benchmarks/bigquerybench/agent.py new file mode 100644 index 0000000000..1e4da954c0 --- /dev/null +++ b/benchmarks/bigquerybench/agent.py @@ -0,0 +1,182 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""BigQueryBench evaluation agent. + +Uses BigQueryToolset with read-only defaults against BigQuery public +datasets, and SkillToolset for skill-based workflows. Override +write_mode via BQ_EVAL_WRITE_MODE env var when evaluating AI/ML +tools (forecast, detect_anomalies, etc.). +""" + +from functools import cached_property +import logging +import os +import pathlib + +from google.adk.agents.llm_agent import LlmAgent +from google.adk.code_executors.unsafe_local_code_executor import UnsafeLocalCodeExecutor +from google.adk.models.google_llm import Gemini +from google.adk.skills import load_skill_from_dir +from google.adk.tools.skill_toolset import SkillToolset +from google.genai import types as genai_types + +logger = logging.getLogger(__name__) + +# ── BigQuery toolset (optional — requires ADC) ─────────────────── +bigquery_toolset = None +try: + from google.adk.tools.bigquery.bigquery_credentials import BigQueryCredentialsConfig + from google.adk.tools.bigquery.bigquery_toolset import BigQueryToolset + from google.adk.tools.bigquery.config import BigQueryToolConfig + from google.adk.tools.bigquery.config import WriteMode + import google.auth + + _WRITE_MODE_MAP = { + "blocked": WriteMode.BLOCKED, + "protected": WriteMode.PROTECTED, + "allowed": WriteMode.ALLOWED, + } + + _write_mode_str = os.environ.get("BQ_EVAL_WRITE_MODE", "blocked").lower() + _write_mode = _WRITE_MODE_MAP.get(_write_mode_str, WriteMode.BLOCKED) + + application_default_credentials, project = google.auth.default() + if not project and not os.environ.get("GOOGLE_CLOUD_PROJECT"): + raise EnvironmentError("No GCP project found. Set GOOGLE_CLOUD_PROJECT.") + credentials_config = BigQueryCredentialsConfig( + credentials=application_default_credentials, + ) + + tool_config = BigQueryToolConfig( + write_mode=_write_mode, + max_query_result_rows=50, + ) + + bigquery_toolset = BigQueryToolset( + credentials_config=credentials_config, + bigquery_tool_config=tool_config, + ) +except Exception as e: + logger.warning( + "BigQuery toolset unavailable (%s). " + "Skill-only evaluation will still work.", + e, + ) + +# ── Skill toolset ────────────────────────────────────────────────── +_SKILLS_DIR = pathlib.Path(__file__).parent / "skills" + +_SKILL_NAMES = [ + "bq-sql-analyst", +] + +_skills = [load_skill_from_dir(_SKILLS_DIR / name) for name in _SKILL_NAMES] + +skill_toolset = SkillToolset( + skills=_skills, + code_executor=UnsafeLocalCodeExecutor(), +) + + +# ── Model (Vertex AI + API key) ────────────────────────────────── +class _VertexGemini(Gemini): + """Gemini subclass that uses vertexai=True with an API key.""" + + @cached_property + def api_client(self): + from google.genai import Client + + return Client( + vertexai=True, + api_key=os.environ.get("GOOGLE_CLOUD_API_KEY"), + http_options=genai_types.HttpOptions( + headers=self._tracking_headers(), + retry_options=self.retry_options, + base_url=self.base_url, + ), + ) + + +_SKILL_INSTRUCTION = """\ +You are a data analyst with access to skills. + +Workflow for skill-based tasks: +1. Use list_skills to discover available skills. +2. Use load_skill to read the skill's instructions. +3. Use load_skill_resource to examine references, sample data, + or templates from the skill. +4. Follow the skill's instructions — this may involve running + the skill's scripts via run_skill_script. +5. Present results clearly. + +IMPORTANT: Only use the tools available to you (list_skills, +load_skill, load_skill_resource, run_skill_script). Do NOT +attempt to call tools that are not listed. +""" + +_BQ_INSTRUCTION = """\ +You are a data analyst with access to BigQuery tools and skills. + +Workflow for direct BigQuery queries: +1. Always explore the schema first: use list_dataset_ids, + list_table_ids, and get_table_info to understand the data + before writing any SQL. +2. Use execute_sql to run queries. Prefer explicit column names + over SELECT *. +3. For forecasting, anomaly detection, or contribution analysis, + use the dedicated tools (forecast, detect_anomalies, + analyze_contribution) instead of raw SQL. +4. Present results clearly with column headers and values. + +Workflow for skill-based tasks: +1. Use list_skills to discover available skills. +2. Use load_skill to read the skill's instructions. +3. Use load_skill_resource to examine references, sample data, + or templates from the skill. +4. Follow the skill's instructions — this may involve calling + BigQuery tools (get_table_info, execute_sql) or running + the skill's scripts via run_skill_script. +5. Present results clearly. + +All public datasets are in project "bigquery-public-data". +""" + +_INSTRUCTION = _BQ_INSTRUCTION if bigquery_toolset else _SKILL_INSTRUCTION + +_api_key = os.environ.get("GOOGLE_CLOUD_API_KEY") +_model = ( + _VertexGemini( + model="gemini-3-flash-preview", + retry_options=genai_types.HttpRetryOptions( + initialDelay=2, + expBase=2, + attempts=5, + ), + ) + if _api_key + else "gemini-3-flash-preview" +) + +root_agent = LlmAgent( + model=_model, + name="bigquerybench_agent", + description=( + "Agent for BigQuery data exploration, SQL execution, and" + " AI/ML operations against public datasets. Also supports" + " skill-based workflows via SkillToolset." + ), + instruction=_INSTRUCTION, + tools=[t for t in [bigquery_toolset, skill_toolset] if t], +) diff --git a/benchmarks/bigquerybench/eval_sets/bigquerybench_eval.json b/benchmarks/bigquerybench/eval_sets/bigquerybench_eval.json new file mode 100644 index 0000000000..2fc87f96bd --- /dev/null +++ b/benchmarks/bigquerybench/eval_sets/bigquerybench_eval.json @@ -0,0 +1,173 @@ +{ + "eval_set_id": "bigquerybench-adk-v1", + "name": "BigQueryBench ADK Evaluation", + "description": "Skill invocation evaluation: verify the agent calls the correct skill tools with the correct args, and follows skill instructions to produce correct results.", + "eval_cases": [ + { + "eval_id": "skill_list_skills", + "conversation": [ + { + "invocation_id": "inv-skill-list-01", + "user_content": { + "parts": [{"text": "What skills are available for me to use?"}], + "role": "user" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "list_skills", "args": {}} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "rubrics": [ + { + "rubric_id": "lists_bq_skill", + "rubric_content": {"text_property": "The response mentions the bq-sql-analyst skill by name."} + }, + { + "rubric_id": "includes_description", + "rubric_content": {"text_property": "The response includes a description of what the skill can do."} + } + ], + "creation_timestamp": 0.0 + }, + { + "eval_id": "skill_load_sql_analyst", + "conversation": [ + { + "invocation_id": "inv-skill-load-01", + "user_content": { + "parts": [{"text": "Load the bq-sql-analyst skill and tell me what it can do."}], + "role": "user" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "rubrics": [ + { + "rubric_id": "describes_capabilities", + "rubric_content": {"text_property": "The response describes the skill's capabilities such as SQL analysis or data formatting."} + }, + { + "rubric_id": "mentions_scripts", + "rubric_content": {"text_property": "The response mentions available scripts or references provided by the skill."} + } + ], + "creation_timestamp": 0.0 + }, + { + "eval_id": "skill_load_reference", + "conversation": [ + { + "invocation_id": "inv-skill-ref-01", + "user_content": { + "parts": [{"text": "Using the bq-sql-analyst skill, load the public datasets reference so I know what data is available."}], + "role": "user" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}}, + {"name": "load_skill_resource", "args": {"skill_name": "bq-sql-analyst", "path": "references/public-datasets.md"}} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "rubrics": [ + { + "rubric_id": "shows_datasets", + "rubric_content": {"text_property": "The response contains information about BigQuery public datasets such as usa_names, samples, or austin_bikeshare."} + }, + { + "rubric_id": "loaded_skill_first", + "rubric_content": {"text_property": "The agent loaded the skill instructions before loading the resource."} + } + ], + "creation_timestamp": 0.0 + }, + { + "eval_id": "skill_query_with_reference", + "conversation": [ + { + "invocation_id": "inv-skill-query-01", + "user_content": { + "parts": [{"text": "Load the bq-sql-analyst skill and then load its public-datasets reference. Summarize the key datasets listed in that reference document."}], + "role": "user" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}}, + {"name": "load_skill_resource", "args": {"skill_name": "bq-sql-analyst", "path": "references/public-datasets.md"}} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "rubrics": [ + { + "rubric_id": "consulted_reference", + "rubric_content": {"text_property": "The agent loaded the public-datasets reference from the skill."} + }, + { + "rubric_id": "summarizes_datasets", + "rubric_content": {"text_property": "The response summarizes datasets mentioned in the reference document."} + }, + { + "rubric_id": "followed_workflow", + "rubric_content": {"text_property": "The agent loaded the skill instructions before loading the resource."} + } + ], + "creation_timestamp": 0.0 + }, + { + "eval_id": "skill_run_format_script", + "conversation": [ + { + "invocation_id": "inv-skill-script-01", + "user_content": { + "parts": [{"text": "Use the bq-sql-analyst skill's format_results.py script to format a table with header 'name,count' and rows 'Alice,5;Bob,3;Carol,8'. Load the skill first."}], + "role": "user" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}}, + {"name": "run_skill_script", "args": {"skill_name": "bq-sql-analyst", "script_path": "scripts/format_results.py"}} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "rubrics": [ + { + "rubric_id": "loaded_before_run", + "rubric_content": {"text_property": "The agent loaded the skill instructions before running the script."} + }, + { + "rubric_id": "output_has_table", + "rubric_content": {"text_property": "The output contains a formatted table with the data for Alice, Bob, and Carol."} + }, + { + "rubric_id": "has_columns", + "rubric_content": {"text_property": "The formatted output includes column headers 'name' and 'count'."} + } + ], + "creation_timestamp": 0.0 + } + ] +} diff --git a/benchmarks/bigquerybench/metrics.py b/benchmarks/bigquerybench/metrics.py new file mode 100644 index 0000000000..929bd49321 --- /dev/null +++ b/benchmarks/bigquerybench/metrics.py @@ -0,0 +1,355 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Metrics for BigQueryBench skill evaluation. + +Three metrics: +1. tool_invocation_score — trace-based, checks tool names +2. tool_args_score — trace-based, checks key tool arguments +3. instruction_adherence_score — LLM-as-judge, checks rubrics + + def metric_fn( + eval_metric: EvalMetric, + actual_invocations: list[Invocation], + expected_invocations: Optional[list[Invocation]], + conversation_scenario: Optional[ConversationScenario] = None, + ) -> EvaluationResult +""" + +from __future__ import annotations + +import asyncio +import logging +import os +import re +from typing import Optional + +from google.adk.evaluation.eval_case import ConversationScenario +from google.adk.evaluation.eval_case import get_all_tool_calls +from google.adk.evaluation.eval_case import Invocation +from google.adk.evaluation.eval_metrics import EvalMetric +from google.adk.evaluation.eval_metrics import EvalStatus +from google.adk.evaluation.eval_rubrics import Rubric +from google.adk.evaluation.evaluator import EvaluationResult +from google.adk.evaluation.evaluator import PerInvocationResult +import google.genai +from google.genai import types as genai_types + +logger = logging.getLogger(__name__) + + +def _get_tool_calls(invocations: list[Invocation]): + """Yield (name, args_dict) for every tool call in the trace.""" + for inv in invocations: + for tc in get_all_tool_calls(inv.intermediate_data): + yield tc.name, (tc.args or {}) + + +def _make_per_invocation( + actual_invocations: list[Invocation], + expected_invocations: Optional[list[Invocation]], + score: float, + status: EvalStatus, +) -> list[PerInvocationResult]: + results = [] + for i, actual in enumerate(actual_invocations): + expected = None + if expected_invocations and i < len(expected_invocations): + expected = expected_invocations[i] + results.append( + PerInvocationResult( + actual_invocation=actual, + expected_invocation=expected, + score=score, + eval_status=status, + ) + ) + return results + + +# ── Metric 1: correct tools invoked ────────────────────────────── + + +def tool_invocation_score( + eval_metric: EvalMetric, + actual_invocations: list[Invocation], + expected_invocations: Optional[list[Invocation]], + conversation_scenario: Optional[ConversationScenario] = None, +) -> EvaluationResult: + """Score = fraction of expected skill tool names present in the trace. + + Checks that the agent called the right skill functions (e.g. + ``list_skills``, ``load_skill``, ``load_skill_resource``, + ``run_skill_script``). Order does not matter; extra tool calls + are ignored. + + Score = |expected_names ∩ actual_names| / |expected_names|. + Pass threshold: 1.0 (all expected tools must be called). + """ + if not expected_invocations: + return EvaluationResult( + overall_score=1.0, + overall_eval_status=EvalStatus.PASSED, + ) + + expected_names = {name for name, _ in _get_tool_calls(expected_invocations)} + actual_names = {name for name, _ in _get_tool_calls(actual_invocations)} + + if not expected_names: + score = 1.0 + else: + matched = expected_names & actual_names + score = len(matched) / len(expected_names) + + status = EvalStatus.PASSED if score >= 1.0 else EvalStatus.FAILED + + return EvaluationResult( + overall_score=score, + overall_eval_status=status, + per_invocation_results=_make_per_invocation( + actual_invocations, + expected_invocations, + score, + status, + ), + ) + + +# ── Metric 2: correct args on key tool calls ───────────────────── + +# Args that identify the *target skill* — these are what we check. +# We only verify that the agent invoked the correct skill tools +# with the correct skill name, resource path, and script path. +_KEY_ARGS = frozenset({ + "name", # load_skill(name=...) + "skill_name", # load_skill_resource / run_skill_script + "path", # load_skill_resource(path=...) + "script_path", # run_skill_script(script_path=...) +}) + + +def tool_args_score( + eval_metric: EvalMetric, + actual_invocations: list[Invocation], + expected_invocations: Optional[list[Invocation]], + conversation_scenario: Optional[ConversationScenario] = None, +) -> EvaluationResult: + """Score = fraction of expected (tool, key-arg) pairs matched. + + For each expected skill tool call that has ``name``, + ``skill_name``, ``path``, or ``script_path`` in its args, check + that the agent made a call to the *same tool* with the *same + value* for that arg. This verifies the agent invoked the correct + skill with the correct resources. + + Score = matched_pairs / expected_pairs. Pass threshold: 1.0. + If no key args exist in the expected trace, score is 1.0 (vacuous). + """ + if not expected_invocations: + return EvaluationResult( + overall_score=1.0, + overall_eval_status=EvalStatus.PASSED, + ) + + # Build expected set: (tool_name, arg_key, arg_value). + expected_pairs: set[tuple[str, str, str]] = set() + for name, args in _get_tool_calls(expected_invocations): + for key in _KEY_ARGS: + if key in args: + expected_pairs.add((name, key, str(args[key]))) + + if not expected_pairs: + # No key args to check — pass vacuously. + return EvaluationResult( + overall_score=1.0, + overall_eval_status=EvalStatus.PASSED, + per_invocation_results=_make_per_invocation( + actual_invocations, + expected_invocations, + 1.0, + EvalStatus.PASSED, + ), + ) + + # Build actual set the same way. + actual_pairs: set[tuple[str, str, str]] = set() + for name, args in _get_tool_calls(actual_invocations): + for key in _KEY_ARGS: + if key in args: + actual_pairs.add((name, key, str(args[key]))) + + matched = expected_pairs & actual_pairs + score = len(matched) / len(expected_pairs) + status = EvalStatus.PASSED if score >= 1.0 else EvalStatus.FAILED + + return EvaluationResult( + overall_score=score, + overall_eval_status=status, + per_invocation_results=_make_per_invocation( + actual_invocations, + expected_invocations, + score, + status, + ), + ) + + +# ── Metric 3: instruction adherence (LLM-as-judge) ──────────────── + +_JUDGE_PROMPT = """\ +You are evaluating an AI agent's behavior. + +For EACH rubric listed below, respond in EXACTLY this format: + +Property: +Rationale: +Verdict: yes or no + +--- + +USER REQUEST: +{user_input} + +TOOL CALLS: +{tool_trace} + +AGENT FINAL RESPONSE: +{final_response} + +RUBRICS TO EVALUATE: +{rubrics_text} +""" + +_VERDICT_RE = re.compile(r"(?<=Verdict: )(.*)") + + +def _extract_text(content) -> str: + """Extract text from a genai Content object.""" + if content and content.parts: + return "\n".join(p.text for p in content.parts if p.text) + return "" + + +def _format_tool_trace(invocations: list[Invocation]) -> str: + """Format tool calls as readable text for the judge.""" + lines = [] + step = 1 + for inv in invocations: + if not inv.intermediate_data: + continue + for tc in get_all_tool_calls(inv.intermediate_data): + args_str = ", ".join(f"{k}={v!r}" for k, v in (tc.args or {}).items()) + lines.append(f"Step {step}: {tc.name}({args_str})") + step += 1 + return "\n".join(lines) if lines else "No tool calls." + + +async def instruction_adherence_score( + actual_invocations: list[Invocation], + rubrics: Optional[list[Rubric]], + judge_model: str = "gemini-3-flash-preview", +) -> EvaluationResult: + """LLM-as-judge: check each rubric against the agent's output. + + For each rubric, prompts a judge model: + "Does the agent satisfy: ?" + Judge answers yes (1.0) or no (0.0) per rubric. + + Score = fraction of rubrics with "yes" verdict. + Pass threshold: 0.75. + """ + if not rubrics: + return EvaluationResult( + overall_score=1.0, + overall_eval_status=EvalStatus.PASSED, + ) + + # Extract conversation data from actual invocations. + user_input = "" + final_response = "" + for inv in actual_invocations: + text = _extract_text(inv.user_content) + if text: + user_input = text + text = _extract_text(inv.final_response) + if text: + final_response = text + + tool_trace = _format_tool_trace(actual_invocations) + + rubrics_text = "\n".join( + f"- {r.rubric_content.text_property}" + for r in rubrics + if r.rubric_content and r.rubric_content.text_property + ) + + prompt = _JUDGE_PROMPT.format( + user_input=user_input or "(empty)", + tool_trace=tool_trace, + final_response=final_response or "(No response)", + rubrics_text=rubrics_text, + ) + + max_attempts = 5 + initial_delay = 2.0 + response_text = "" + for attempt in range(1, max_attempts + 1): + try: + api_key = os.environ.get("GOOGLE_CLOUD_API_KEY", "") + client = google.genai.Client( + vertexai=True, + api_key=api_key, + http_options=genai_types.HttpOptions( + retry_options=genai_types.HttpRetryOptions( + initialDelay=initial_delay, + expBase=2, + attempts=3, + ), + ), + ) + response = await client.aio.models.generate_content( + model=judge_model, + contents=prompt, + ) + response_text = response.text or "" + break + except Exception as e: + if attempt < max_attempts and "429" in str(e): + delay = initial_delay * (2 ** (attempt - 1)) + logger.warning( + "Judge LLM rate-limited (attempt %d/%d), retrying in %.1fs...", + attempt, + max_attempts, + delay, + ) + await asyncio.sleep(delay) + else: + logger.error("Judge LLM call failed: %s", e) + return EvaluationResult( + overall_score=0.0, + overall_eval_status=EvalStatus.FAILED, + ) + + # Parse verdicts. + verdicts = _VERDICT_RE.findall(response_text) + yes_count = sum(1 for v in verdicts if v.strip().lower().startswith("yes")) + total = len(rubrics) + score = yes_count / total if total > 0 else 1.0 + + status = EvalStatus.PASSED if score >= 0.75 else EvalStatus.FAILED + + return EvaluationResult( + overall_score=score, + overall_eval_status=status, + ) diff --git a/benchmarks/bigquerybench/runner.py b/benchmarks/bigquerybench/runner.py new file mode 100644 index 0000000000..aae6a85e32 --- /dev/null +++ b/benchmarks/bigquerybench/runner.py @@ -0,0 +1,349 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""BigQueryBench evaluation runner. + +Evaluates skill invocation correctness (trace-based) and instruction +adherence (LLM-as-judge with rubrics). + +Usage: + python -m benchmarks.bigquerybench.runner + python -m benchmarks.bigquerybench.runner --filter skill_load + python -m benchmarks.bigquerybench.runner --num-runs 3 + python -m benchmarks.bigquerybench.runner --dry-run + +Environment variables: + GOOGLE_CLOUD_PROJECT — GCP project for BigQuery API calls + GOOGLE_API_KEY — API key for Google AI Studio + GOOGLE_GENAI_USE_VERTEXAI — Set to 1 for Vertex AI backend + BQ_EVAL_WRITE_MODE — blocked / protected / allowed +""" + +from __future__ import annotations + +import argparse +import asyncio +import json +import logging +import pathlib +import sys +import time +from typing import Optional +import uuid + +from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService +from google.adk.evaluation.eval_case import Invocation +from google.adk.evaluation.eval_metrics import EvalMetric +from google.adk.evaluation.eval_set import EvalSet +from google.adk.evaluation.evaluation_generator import EvaluationGenerator +from google.adk.memory.in_memory_memory_service import InMemoryMemoryService +from google.adk.runners import Runner +from google.adk.sessions.in_memory_session_service import InMemorySessionService +from google.adk.utils.context_utils import Aclosing + +from .metrics import instruction_adherence_score +from .metrics import tool_args_score +from .metrics import tool_invocation_score + +logger = logging.getLogger(__name__) + +_BENCH_DIR = pathlib.Path(__file__).parent +_DEFAULT_EVAL_SET = _BENCH_DIR / "eval_sets" / "bigquerybench_eval.json" + + +def load_eval_set(path: pathlib.Path) -> EvalSet: + with open(path) as f: + data = json.load(f) + return EvalSet.model_validate(data) + + +def print_header(): + print() + print("=" * 72) + print(" BigQueryBench — Skill Evaluation") + print("=" * 72) + print() + + +def _case_passed(scores: dict[str, float]) -> bool: + trace_ok = ( + scores.get("tool_invocation", 0.0) >= 1.0 + and scores.get("tool_args", 0.0) >= 1.0 + ) + adherence_ok = scores.get("adherence", 1.0) >= 0.75 + return trace_ok and adherence_ok + + +def print_results_table(results: dict[str, dict[str, float]]): + print( + f"{'Eval Case':<34} {'Tools':>6} {'Args':>6} {'Adhere':>7} {'Result':>7}" + ) + print("-" * 72) + for case_id, scores in results.items(): + short_id = case_id[:33] + tools = scores.get("tool_invocation", 0.0) + args = scores.get("tool_args", 0.0) + adhere = scores.get("adherence", 1.0) + mark = "PASS" if _case_passed(scores) else "FAIL" + print( + f"{short_id:<34} {tools:>6.2f} {args:>6.2f} {adhere:>7.2f} {mark:>4}" + ) + print("-" * 72) + + +def print_summary( + results: dict[str, dict[str, float]], + num_cases: int, + elapsed: float, +): + n = max(len(results), 1) + passed = sum(1 for s in results.values() if _case_passed(s)) + avg_tools = sum(s.get("tool_invocation", 0.0) for s in results.values()) / n + avg_args = sum(s.get("tool_args", 0.0) for s in results.values()) / n + avg_adhere = sum(s.get("adherence", 1.0) for s in results.values()) / n + pct = (passed / max(num_cases, 1)) * 100 + + print() + print("=" * 72) + print(" Summary") + print("=" * 72) + print(f" Cases: {passed}/{num_cases} ({pct:.1f}%)") + print(f" Avg Tool Match: {avg_tools:.2f}") + print(f" Avg Args Match: {avg_args:.2f}") + print(f" Avg Adherence: {avg_adhere:.2f}") + print(f" Elapsed: {elapsed:.1f}s") + print("=" * 72) + + +async def run_single_eval_case(root_agent, eval_case) -> list[Invocation]: + session_service = InMemorySessionService() + artifact_service = InMemoryArtifactService() + memory_service = InMemoryMemoryService() + + app_name = "bigquerybench_eval" + user_id = "eval_user" + session_id = str(uuid.uuid4()) + + await session_service.create_session( + app_name=app_name, + user_id=user_id, + state={}, + session_id=session_id, + ) + + async with Runner( + app_name=app_name, + agent=root_agent, + artifact_service=artifact_service, + session_service=session_service, + memory_service=memory_service, + ) as runner: + events = [] + for invocation in eval_case.conversation: + user_content = invocation.user_content + + async with Aclosing( + runner.run_async( + user_id=user_id, + session_id=session_id, + new_message=user_content, + ) + ) as agen: + invocation_id = None + async for event in agen: + if not invocation_id: + invocation_id = event.invocation_id + from google.adk.events.event import Event + + events.append( + Event( + content=user_content, + author="user", + invocation_id=invocation_id, + ) + ) + events.append(event) + + return EvaluationGenerator.convert_events_to_eval_invocations(events) + + +async def score_invocations( + actual: list[Invocation], + expected: Optional[list[Invocation]], + rubrics=None, +) -> dict[str, float]: + metric = EvalMetric(metric_name="bigquerybench") + + r1 = tool_invocation_score(metric, actual, expected) + r2 = tool_args_score(metric, actual, expected) + + scores = { + "tool_invocation": r1.overall_score or 0.0, + "tool_args": r2.overall_score or 0.0, + } + + if rubrics: + r3 = await instruction_adherence_score(actual, rubrics) + scores["adherence"] = r3.overall_score or 0.0 + + return scores + + +_TRACE_ARGS = frozenset({ + "name", + "skill_name", + "path", + "script_path", +}) + + +def _print_trace(actual_invocations: list[Invocation]): + """Print the tool-call trace for debugging.""" + from google.adk.evaluation.eval_case import get_all_tool_calls + + for inv in actual_invocations: + for tc in get_all_tool_calls(inv.intermediate_data): + args_summary = ", ".join( + f"{k}={v!r}" for k, v in (tc.args or {}).items() if k in _TRACE_ARGS + ) + print(f" -> {tc.name}({args_summary})") + + +async def run_evaluation( + eval_set_path: Optional[pathlib.Path] = None, + num_runs: int = 1, + filter_str: Optional[str] = None, +) -> dict[str, dict[str, float]]: + path = eval_set_path or _DEFAULT_EVAL_SET + eval_set = load_eval_set(path) + + from .agent import root_agent + + cases = eval_set.eval_cases + if filter_str: + cases = [c for c in cases if filter_str in c.eval_id] + if not cases: + print(f" No eval cases matched filter: {filter_str!r}") + return {} + + results: dict[str, dict[str, float]] = {} + + for idx, eval_case in enumerate(cases, 1): + eval_id = eval_case.eval_id + print(f"\n[{idx}/{len(cases)}] {eval_id}") + + run_scores: list[dict[str, float]] = [] + for run in range(num_runs): + if num_runs > 1: + print(f" Run {run + 1}/{num_runs}...") + + try: + actual = await run_single_eval_case(root_agent, eval_case) + _print_trace(actual) + + scores = await score_invocations( + actual, eval_case.conversation, eval_case.rubrics + ) + run_scores.append(scores) + + tools = scores["tool_invocation"] + args = scores["tool_args"] + adhere = scores.get("adherence", 1.0) + mark = "PASS" if _case_passed(scores) else "FAIL" + parts = [f"tools={tools:.2f}", f"args={args:.2f}"] + if "adherence" in scores: + parts.append(f"adherence={adhere:.2f}") + print(f" {' '.join(parts)} {mark}") + + except Exception as e: + logger.error("Error running %s: %s", eval_id, e) + print(f" ERROR: {e}") + run_scores.append({"tool_invocation": 0.0, "tool_args": 0.0}) + + avg: dict[str, float] = {} + for key in ("tool_invocation", "tool_args", "adherence"): + vals = [s[key] for s in run_scores if key in s] + if vals: + avg[key] = sum(vals) / len(vals) + results[eval_id] = avg + + return results + + +def main(): + parser = argparse.ArgumentParser( + description="BigQueryBench trace-based evaluation runner", + ) + parser.add_argument( + "--eval-set", + type=pathlib.Path, + default=None, + ) + parser.add_argument( + "--num-runs", + type=int, + default=1, + ) + parser.add_argument( + "--filter", + type=str, + default=None, + ) + parser.add_argument( + "--dry-run", + action="store_true", + ) + args = parser.parse_args() + + logging.basicConfig(level=logging.WARNING) + + if args.dry_run: + path = args.eval_set or _DEFAULT_EVAL_SET + es = load_eval_set(path) + print(f"Eval set: {es.name}") + print(f"Cases: {len(es.eval_cases)}") + for case in es.eval_cases: + tools = [ + t.name for t in case.conversation[0].intermediate_data.tool_uses or [] + ] + n_rubrics = len(case.rubrics) if case.rubrics else 0 + rubric_info = f" ({n_rubrics} rubrics)" if n_rubrics else "" + print(f" {case.eval_id}: {' -> '.join(tools)}{rubric_info}") + print("\nJSON valid.") + sys.exit(0) + + print_header() + start = time.time() + + results = asyncio.run( + run_evaluation( + eval_set_path=args.eval_set, + num_runs=args.num_runs, + filter_str=args.filter, + ) + ) + + elapsed = time.time() - start + num_cases = len(results) + + print() + print_results_table(results) + print_summary(results, num_cases, elapsed) + + all_pass = all(_case_passed(s) for s in results.values()) + sys.exit(0 if all_pass else 1) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/bigquerybench/skills/bq-sql-analyst/SKILL.md b/benchmarks/bigquerybench/skills/bq-sql-analyst/SKILL.md new file mode 100644 index 0000000000..ec7f8f5bac --- /dev/null +++ b/benchmarks/bigquerybench/skills/bq-sql-analyst/SKILL.md @@ -0,0 +1,34 @@ +--- +name: bq-sql-analyst +description: Analyze BigQuery public datasets with SQL — explore schemas, write queries, and format results. +--- + +# BigQuery SQL Analyst Skill + +Explore and analyze BigQuery public datasets by examining schemas, +writing SQL queries, and presenting formatted results. + +## Available Scripts + +### `format_results.py` + +Formats raw query output as a readable markdown table. + +**Usage**: `run_skill_script(skill_name="bq-sql-analyst", script_path="scripts/format_results.py", args={"header": "name,count", "rows": "Alice,5;Bob,3"})` + +Arguments: +- `header`: Comma-separated column names +- `rows`: Semicolon-separated rows, each with comma-separated values +- `title` (optional): Table title + +## References + +- [public-datasets.md](./references/public-datasets.md) — Commonly used BigQuery public datasets and their schemas + +## Workflow + +1. Use `load_skill` to read these instructions. +2. Use `load_skill_resource` to review the public datasets reference. +3. Use BigQuery tools (`get_table_info`, `execute_sql`) to explore and query data. +4. Optionally use `run_skill_script` to format results. +5. Present findings to the user. diff --git a/benchmarks/bigquerybench/skills/bq-sql-analyst/references/public-datasets.md b/benchmarks/bigquerybench/skills/bq-sql-analyst/references/public-datasets.md new file mode 100644 index 0000000000..bc08041c53 --- /dev/null +++ b/benchmarks/bigquerybench/skills/bq-sql-analyst/references/public-datasets.md @@ -0,0 +1,34 @@ +# BigQuery Public Datasets Reference + +Commonly used datasets in the `bigquery-public-data` project. + +## usa_names + +Baby name data from US Social Security Administration. + +| Table | Description | +|-------|-------------| +| `usa_1910_current` | Names, gender, state, year, count from 1910 to present | + +Key columns: `name` (STRING), `gender` (STRING), `state` (STRING), `year` (INT64), `number` (INT64) + +## samples + +Sample datasets provided by BigQuery. + +| Table | Description | +|-------|-------------| +| `shakespeare` | Every word in every Shakespeare work with word count | + +Key columns: `word` (STRING), `word_count` (INT64), `corpus` (STRING), `corpus_date` (INT64) + +## austin_bikeshare + +Austin B-cycle bikeshare trip data. + +| Table | Description | +|-------|-------------| +| `bikeshare_trips` | Individual trip records with start/end stations and times | +| `bikeshare_stations` | Station locations and metadata | + +Key columns (trips): `trip_id`, `start_station_name`, `end_station_name`, `duration_minutes`, `start_time` diff --git a/benchmarks/bigquerybench/skills/bq-sql-analyst/scripts/format_results.py b/benchmarks/bigquerybench/skills/bq-sql-analyst/scripts/format_results.py new file mode 100644 index 0000000000..86fc250e98 --- /dev/null +++ b/benchmarks/bigquerybench/skills/bq-sql-analyst/scripts/format_results.py @@ -0,0 +1,51 @@ +"""Format query results as a markdown table.""" + +import sys + + +def parse_args(args): + params = {} + i = 0 + while i < len(args): + if args[i].startswith("--") and i + 1 < len(args): + params[args[i][2:]] = args[i + 1] + i += 2 + elif "=" in args[i]: + key, value = args[i].split("=", 1) + params[key.lstrip("-")] = value + i += 1 + else: + i += 1 + return params + + +def main(): + params = parse_args(sys.argv[1:]) + header = params.get("header", "") + rows_str = params.get("rows", "") + title = params.get("title", "") + + if not header: + print("Error: --header is required") + sys.exit(1) + + cols = [c.strip() for c in header.split(",")] + + if title: + print(f"## {title}") + print() + + print("| " + " | ".join(cols) + " |") + print("| " + " | ".join("---" for _ in cols) + " |") + + if rows_str: + for row in rows_str.split(";"): + vals = [v.strip() for v in row.split(",")] + # Pad if needed + while len(vals) < len(cols): + vals.append("") + print("| " + " | ".join(vals[: len(cols)]) + " |") + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillsbench/README.md b/benchmarks/skillsbench/README.md new file mode 100644 index 0000000000..5bb8a8a818 --- /dev/null +++ b/benchmarks/skillsbench/README.md @@ -0,0 +1,131 @@ +# SkillsBench Evaluation Harness for ADK + +Evaluates ADK's `SkillToolset` against tasks adapted from the +[SkillsBench](https://github.com/benchflow-ai/skillsbench) benchmark. + +## Overview + +This harness adapts 8 representative SkillsBench tasks as ADK skills and +evaluates them through the ADK evaluation framework. It tests whether an +agent can discover, load, and execute skills using the `SkillToolset` +tools: `list_skills`, `load_skill`, `load_skill_resource`, and +`run_skill_script`. + +## Task Categories + +| # | Category | Skill | What it tests | +|---|----------|-------|---------------| +| 1 | Data Analysis | csv-aggregation | skill discovery + script execution | +| 2 | File Processing | json-transform | load_skill_resource + script | +| 3 | Web Scraping | html-extraction | skill with references | +| 4 | API Interaction | rest-client | multi-step skill usage | +| 5 | Text Transformation | regex-replace | simple script execution | +| 6 | Code Generation | function-scaffold | skill instruction following | +| 7 | Math Computation | statistical-calc | output validation | +| 8 | System Admin | log-parsing | complex skill with metadata | + +## Setup + +```bash +# From repo root +uv venv --python "python3.11" ".venv" +source .venv/bin/activate +uv sync --all-extras + +# Set your API key +export GOOGLE_API_KEY="your-key-here" +``` + +## Usage + +### Run with ADK CLI + +```bash +# Interactive web UI +adk web benchmarks/skillsbench + +# Run evaluation via ADK eval +adk eval benchmarks/skillsbench \ + benchmarks/skillsbench/eval_sets/skillsbench_eval.json +``` + +### Run standalone scorer + +```bash +python benchmarks/skillsbench/runner.py +python benchmarks/skillsbench/runner.py --num-runs 3 +python benchmarks/skillsbench/runner.py --eval-set path/to/custom_eval.json +``` + +### Output format + +The standalone runner produces a per-task results table and a +leaderboard-format summary: + +``` +============================================================ + Leaderboard Summary +============================================================ + Model: gemini-2.5-flash + Framework: ADK SkillToolset + Tasks: X/8 (XX.X%) + Avg Discovery: X.XX + Avg Tool Usage: X.XX + Elapsed: XX.Xs +============================================================ +``` + +## Custom Metrics + +Three metrics are provided in `metrics.py`: + +- **skill_discovery_score** — 1.0 if the agent called both `list_skills` + and `load_skill`, else 0.0 +- **tool_usage_score** — Fraction of expected tool calls that were made + (ANY_ORDER matching) +- **skillsbench_binary_score** — 1.0 if the final response contains all + expected reference lines, else 0.0 + +Reference these in eval configs via their dotted paths: +``` +benchmarks.skillsbench.metrics.skill_discovery_score +benchmarks.skillsbench.metrics.tool_usage_score +benchmarks.skillsbench.metrics.skillsbench_binary_score +``` + +## Directory Structure + +``` +benchmarks/skillsbench/ +├── __init__.py +├── README.md +├── agent.py # ADK agent with SkillToolset +├── skills/ # 8 adapted SkillsBench tasks +│ ├── csv-aggregation/ +│ ├── json-transform/ +│ ├── html-extraction/ +│ ├── rest-client/ +│ ├── regex-replace/ +│ ├── function-scaffold/ +│ ├── statistical-calc/ +│ └── log-parsing/ +├── eval_sets/ +│ └── skillsbench_eval.json # EvalSet with 8 cases +├── metrics.py # Custom metric functions +└── runner.py # Standalone runner +``` + +## Adding New Tasks + +1. Create a skill directory under `skills/` with a `SKILL.md` following + the [Agent Skills spec](https://github.com/benchflow-ai/skillsbench) +2. Add scripts under `skills//scripts/` +3. Add references under `skills//references/` (optional) +4. Add the skill name to `_SKILL_NAMES` in `agent.py` +5. Add a new `EvalCase` entry to `eval_sets/skillsbench_eval.json` + +## Security Note + +This harness uses `UnsafeLocalCodeExecutor` for skill script execution. +For production or untrusted skill scripts, use `ContainerCodeExecutor` +or `VertexAICodeExecutor` instead. diff --git a/benchmarks/skillsbench/__init__.py b/benchmarks/skillsbench/__init__.py new file mode 100644 index 0000000000..196d315208 --- /dev/null +++ b/benchmarks/skillsbench/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""SkillsBench evaluation harness for ADK SkillToolset.""" diff --git a/benchmarks/skillsbench/agent.py b/benchmarks/skillsbench/agent.py new file mode 100644 index 0000000000..aaa70f5ce1 --- /dev/null +++ b/benchmarks/skillsbench/agent.py @@ -0,0 +1,73 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""SkillsBench evaluation agent with SkillToolset and Gemini Flash. + +This agent loads all skills from the skills/ directory and uses +SkillToolset to provide list_skills, load_skill, load_skill_resource, +and run_skill_script tools. It is designed to be evaluated against +the SkillsBench benchmark tasks. + +WARNING: This agent uses UnsafeLocalCodeExecutor for script execution. +For production use, prefer ContainerCodeExecutor or VertexAICodeExecutor. +""" + +import pathlib + +from google.adk import Agent +from google.adk.code_executors.unsafe_local_code_executor import UnsafeLocalCodeExecutor +from google.adk.skills import load_skill_from_dir +from google.adk.tools.skill_toolset import SkillToolset + +_SKILLS_DIR = pathlib.Path(__file__).parent / "skills" + +_SKILL_NAMES = [ + "csv-aggregation", + "json-transform", + "html-extraction", + "rest-client", + "regex-replace", + "function-scaffold", + "statistical-calc", + "log-parsing", +] + +_skills = [load_skill_from_dir(_SKILLS_DIR / name) for name in _SKILL_NAMES] + +skill_toolset = SkillToolset( + skills=_skills, + code_executor=UnsafeLocalCodeExecutor(), +) + +root_agent = Agent( + model="gemini-3-flash-preview", + name="skillsbench_agent", + description=( + "An agent that completes tasks by discovering and using" + " available skills from the SkillsBench benchmark." + ), + instruction=( + "You are an agent that completes tasks by discovering and using" + " available skills. Follow this workflow:\n" + "1. Use list_skills to find relevant skills for the task.\n" + "2. Use load_skill to read the skill's instructions carefully.\n" + "3. Use load_skill_resource to examine references or sample data" + " if available.\n" + "4. Use run_skill_script to run the skill's scripts with" + " appropriate arguments.\n" + "5. Interpret the output and present a clear answer.\n\n" + "Always check skill instructions before executing scripts." + ), + tools=[skill_toolset], +) diff --git a/benchmarks/skillsbench/eval_sets/skillsbench_eval.json b/benchmarks/skillsbench/eval_sets/skillsbench_eval.json new file mode 100644 index 0000000000..3a9eee6b56 --- /dev/null +++ b/benchmarks/skillsbench/eval_sets/skillsbench_eval.json @@ -0,0 +1,230 @@ +{ + "eval_set_id": "skillsbench-adk-v1", + "name": "SkillsBench ADK Evaluation", + "description": "8 representative SkillsBench tasks adapted as ADK skills to evaluate SkillToolset with Gemini Flash.", + "eval_cases": [ + { + "eval_id": "data_analysis_csv_aggregation", + "conversation": [ + { + "invocation_id": "inv-csv-agg-01", + "user_content": { + "parts": [{"text": "Aggregate the sample employee CSV data by department and show salary statistics for each department."}], + "role": "user" + }, + "final_response": { + "parts": [{"text": "Group: Engineering\n count: 3\n sum: 285000\n mean: 95000\nGroup: Marketing\n count: 3\n sum: 214000\nGroup: Sales\n count: 2\n sum: 157000"}], + "role": "model" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "list_skills", "args": {}}, + {"name": "load_skill", "args": {"skill_name": "csv-aggregation"}}, + {"name": "load_skill_resource", "args": {"skill_name": "csv-aggregation", "resource_type": "references", "resource_id": "sample-data.md"}}, + {"name": "run_skill_script", "args": {"skill_name": "csv-aggregation", "script_path": "scripts/aggregate.py", "args": {"group_col": "department", "metric_col": "salary"}}} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "creation_timestamp": 0.0 + }, + { + "eval_id": "file_processing_json_transform", + "conversation": [ + { + "invocation_id": "inv-json-tf-01", + "user_content": { + "parts": [{"text": "Flatten the nested user JSON data into a flat structure with dot-notation keys."}], + "role": "user" + }, + "final_response": { + "parts": [{"text": "user.name\nuser.age\nuser.address.city\nuser.address.state\nuser.address.zip"}], + "role": "model" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "list_skills", "args": {}}, + {"name": "load_skill", "args": {"skill_name": "json-transform"}}, + {"name": "load_skill_resource", "args": {"skill_name": "json-transform", "resource_type": "references", "resource_id": "sample-data.md"}}, + {"name": "run_skill_script", "args": {"skill_name": "json-transform", "script_path": "scripts/transform.py", "args": {"flatten": "true"}}} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "creation_timestamp": 0.0 + }, + { + "eval_id": "web_scraping_html_extraction", + "conversation": [ + { + "invocation_id": "inv-html-ext-01", + "user_content": { + "parts": [{"text": "Extract all the product data from the HTML page as a table with product name, price, and stock columns."}], + "role": "user" + }, + "final_response": { + "parts": [{"text": "Product,Price,Stock\nLaptop,999.99,15\nPhone,699.99,42\nTablet,449.99,28"}], + "role": "model" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "list_skills", "args": {}}, + {"name": "load_skill", "args": {"skill_name": "html-extraction"}}, + {"name": "load_skill_resource", "args": {"skill_name": "html-extraction", "resource_type": "references", "resource_id": "sample-page.md"}}, + {"name": "run_skill_script", "args": {"skill_name": "html-extraction", "script_path": "scripts/extract.py", "args": {"target": "table"}}} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "creation_timestamp": 0.0 + }, + { + "eval_id": "api_interaction_rest_client", + "conversation": [ + { + "invocation_id": "inv-rest-01", + "user_content": { + "parts": [{"text": "Use the REST API to fetch the list of users and then get the details for user with ID 2."}], + "role": "user" + }, + "final_response": { + "parts": [{"text": "Bob\nbob@example.com"}], + "role": "model" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "list_skills", "args": {}}, + {"name": "load_skill", "args": {"skill_name": "rest-client"}}, + {"name": "load_skill_resource", "args": {"skill_name": "rest-client", "resource_type": "references", "resource_id": "api-docs.md"}}, + {"name": "run_skill_script", "args": {"skill_name": "rest-client", "script_path": "scripts/request.py", "args": {"method": "GET", "endpoint": "/users"}}}, + {"name": "run_skill_script", "args": {"skill_name": "rest-client", "script_path": "scripts/request.py", "args": {"method": "GET", "endpoint": "/users/2"}}} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "creation_timestamp": 0.0 + }, + { + "eval_id": "text_transformation_regex_replace", + "conversation": [ + { + "invocation_id": "inv-regex-01", + "user_content": { + "parts": [{"text": "Replace all numbers in the text 'Order 123 has 45 items at $67' with the word NUM."}], + "role": "user" + }, + "final_response": { + "parts": [{"text": "Result: Order NUM has NUM items at $NUM\nMatches: 3"}], + "role": "model" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "list_skills", "args": {}}, + {"name": "load_skill", "args": {"skill_name": "regex-replace"}}, + {"name": "run_skill_script", "args": {"skill_name": "regex-replace", "script_path": "scripts/replace.py", "args": {"pattern": "\\d+", "replacement": "NUM", "text": "Order 123 has 45 items at $67"}}} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "creation_timestamp": 0.0 + }, + { + "eval_id": "code_generation_function_scaffold", + "conversation": [ + { + "invocation_id": "inv-scaffold-01", + "user_content": { + "parts": [{"text": "Generate a Python function scaffold for a function called calculate_bmi that takes weight (float) and height (float) and returns a float."}], + "role": "user" + }, + "final_response": { + "parts": [{"text": "def calculate_bmi(weight: float, height: float) -> float:"}], + "role": "model" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "list_skills", "args": {}}, + {"name": "load_skill", "args": {"skill_name": "function-scaffold"}}, + {"name": "run_skill_script", "args": {"skill_name": "function-scaffold", "script_path": "scripts/scaffold.py", "args": {"name": "calculate_bmi", "params": "weight:float,height:float", "returns": "float", "description": "Calculate Body Mass Index"}}} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "creation_timestamp": 0.0 + }, + { + "eval_id": "math_computation_statistical_calc", + "conversation": [ + { + "invocation_id": "inv-stats-01", + "user_content": { + "parts": [{"text": "Compute descriptive statistics (mean, median, standard deviation) for the dataset: 10, 20, 30, 40, 50, 60, 70, 80, 90, 100."}], + "role": "user" + }, + "final_response": { + "parts": [{"text": "Mean: 55.00\nMedian: 55.00\nStd Dev: 28.72"}], + "role": "model" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "list_skills", "args": {}}, + {"name": "load_skill", "args": {"skill_name": "statistical-calc"}}, + {"name": "run_skill_script", "args": {"skill_name": "statistical-calc", "script_path": "scripts/stats.py", "args": {"data": "10,20,30,40,50,60,70,80,90,100"}}} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "creation_timestamp": 0.0 + }, + { + "eval_id": "system_admin_log_parsing", + "conversation": [ + { + "invocation_id": "inv-logs-01", + "user_content": { + "parts": [{"text": "Analyze the system logs and give me a summary showing the count of each log level (ERROR, WARNING, INFO, DEBUG)."}], + "role": "user" + }, + "final_response": { + "parts": [{"text": "ERROR: 3\nWARNING: 2\nINFO: 5\nDEBUG: 2"}], + "role": "model" + }, + "intermediate_data": { + "tool_uses": [ + {"name": "list_skills", "args": {}}, + {"name": "load_skill", "args": {"skill_name": "log-parsing"}}, + {"name": "load_skill_resource", "args": {"skill_name": "log-parsing", "resource_type": "references", "resource_id": "sample-logs.md"}}, + {"name": "run_skill_script", "args": {"skill_name": "log-parsing", "script_path": "scripts/parse.py", "args": {"level": "ALL", "format": "summary"}}} + ], + "tool_responses": [], + "intermediate_responses": [] + }, + "creation_timestamp": 0.0 + } + ], + "creation_timestamp": 0.0 + } + ], + "creation_timestamp": 0.0 +} diff --git a/benchmarks/skillsbench/full_runner.py b/benchmarks/skillsbench/full_runner.py new file mode 100644 index 0000000000..ce730cba3f --- /dev/null +++ b/benchmarks/skillsbench/full_runner.py @@ -0,0 +1,1236 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Full SkillsBench runner — Docker-based with real pytest scoring. + +Builds Docker images per-task from each task's environment/Dockerfile, +runs agent scripts inside the container (where /root/ data files exist), +then runs the real pytest tests inside the same container for binary +pass/fail scoring matching SkillsBench methodology. + +Usage: + python -u -m benchmarks.skillsbench.full_runner + python -u -m benchmarks.skillsbench.full_runner --filter citation-check + python -u -m benchmarks.skillsbench.full_runner --build-only + python -u -m benchmarks.skillsbench.full_runner --skip-tests + +Environment variables: + GOOGLE_API_KEY — API key for authentication + GOOGLE_GENAI_USE_VERTEXAI — Set to 1 for Vertex AI backend +""" + +from __future__ import annotations + +import argparse +import asyncio +import concurrent.futures +import io +import json +import logging +import pathlib +import re +import sys +import tarfile +import threading +import time +import tomllib +from typing import Any +import uuid + +import docker +from google.adk import Agent +from google.adk.agents.invocation_context import InvocationContext +from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService +from google.adk.code_executors.base_code_executor import BaseCodeExecutor +from google.adk.code_executors.code_execution_utils import CodeExecutionInput +from google.adk.code_executors.code_execution_utils import CodeExecutionResult +from google.adk.evaluation.eval_case import get_all_tool_calls +from google.adk.evaluation.eval_case import Invocation +from google.adk.evaluation.evaluation_generator import EvaluationGenerator +from google.adk.events.event import Event +from google.adk.memory.in_memory_memory_service import InMemoryMemoryService +from google.adk.models.google_llm import Gemini +from google.adk.runners import Runner +from google.adk.sessions.in_memory_session_service import InMemorySessionService +from google.adk.skills import load_skill_from_dir +from google.adk.skills.models import Frontmatter +from google.adk.skills.models import Resources +from google.adk.skills.models import Script +from google.adk.skills.models import Skill +from google.adk.tools.base_tool import BaseTool +from google.adk.tools.skill_toolset import SkillToolset +from google.adk.utils.context_utils import Aclosing +from google.genai import types as genai_types +from pydantic import ConfigDict +from pydantic import Field +from typing_extensions import override +import yaml + +logger = logging.getLogger(__name__) + +_DEFAULT_TASKS_DIR = pathlib.Path("/tmp/skillsbench/tasks") +_MODEL_NAME = "gemini-3-flash-preview" + +# ── Timeouts (seconds) ────────────────────────────────────────────── +_DEFAULT_AGENT_TIMEOUT = 900.0 +_DEFAULT_BUILD_TIMEOUT = 600.0 +_DEFAULT_VERIFIER_TIMEOUT = 900.0 + + +# ── helpers ────────────────────────────────────────────────────────── + + +def _slugify(name: str) -> str: + """Convert a name to lowercase kebab-case. + + Lowercases, replaces underscores and spaces with hyphens, + strips non-alphanumeric/non-hyphen chars, collapses runs + of hyphens, and trims leading/trailing hyphens. + """ + s = name.lower() + s = s.replace("_", "-").replace(" ", "-") + s = re.sub(r"[^a-z0-9-]", "", s) + s = re.sub(r"-{2,}", "-", s) + return s.strip("-") + + +def _load_dir(directory: pathlib.Path) -> dict[str, str]: + """Recursively load files from a directory into a dict. + + Mirrors google.adk.skills._utils._load_dir so the runner + does not depend on a private import. + """ + files: dict[str, str] = {} + if directory.exists() and directory.is_dir(): + for file_path in directory.rglob("*"): + if "__pycache__" in file_path.parts: + continue + if file_path.is_file(): + relative = file_path.relative_to(directory) + try: + files[str(relative)] = file_path.read_text(encoding="utf-8") + except UnicodeDecodeError: + continue + return files + + +# ── Docker prereq ──────────────────────────────────────────────────── + + +def ensure_docker_running() -> docker.DockerClient: + """Return a Docker client or fail fast with a clear message.""" + try: + client = docker.from_env() + client.ping() + return client + except Exception as exc: + print( + "\nERROR: Docker is not running or not accessible.\n" + "Please start Docker Desktop and try again.\n" + f" Detail: {exc}\n", + file=sys.stderr, + ) + sys.exit(1) + + +# ── TaskContainerExecutor ──────────────────────────────────────────── + + +class TaskContainerExecutor(BaseCodeExecutor): + """Code executor that runs Python inside a Docker container. + + Unlike ADK's ContainerCodeExecutor (which uses atexit for + cleanup), this gives direct lifecycle control for test + injection after the agent finishes. + """ + + model_config = ConfigDict(arbitrary_types_allowed=True) + + stateful: bool = Field(default=False, frozen=True, exclude=True) + optimize_data_file: bool = Field(default=False, frozen=True, exclude=True) + + _container: object = None + _client: object = None + _cmd_timeout: float = 180.0 # Per-command timeout in seconds + + def start( + self, + image_tag: str, + client: docker.DockerClient, + ) -> None: + """Start a detached container from *image_tag*.""" + self._client = client + self._container = client.containers.run( + image_tag, + command="sleep infinity", + detach=True, + tty=True, + working_dir="/root", + ) + + def _exec_run_with_timeout( + self, + cmd: list[str], + workdir: str = "/root", + timeout: float | None = None, + ) -> tuple[int, bytes, bytes]: + """Run exec_run in a thread with a timeout. + + Returns (exit_code, stdout_bytes, stderr_bytes). + Raises TimeoutError if the command exceeds *timeout*. + """ + timeout = timeout or self._cmd_timeout + + def _run(): + rc, output = self._container.exec_run( + cmd, + workdir=workdir, + demux=True, + ) + return rc, (output[0] or b""), (output[1] or b"") + + with concurrent.futures.ThreadPoolExecutor(1) as pool: + future = pool.submit(_run) + try: + return future.result(timeout=timeout) + except concurrent.futures.TimeoutError: + raise TimeoutError( + f"Command timed out after {timeout}s: {' '.join(cmd[:3])}" + ) + + @override + def execute_code( + self, + invocation_context: InvocationContext, + code_execution_input: CodeExecutionInput, + ) -> CodeExecutionResult: + """Run ``python3 -c `` inside the container.""" + if self._container is None: + return CodeExecutionResult( + stdout="", + stderr="Container not started", + ) + code = code_execution_input.code + try: + rc, out, err = self._exec_run_with_timeout( + ["python3", "-c", code], + ) + except TimeoutError as exc: + return CodeExecutionResult( + stdout="", + stderr=str(exc), + ) + stdout = out.decode("utf-8", errors="replace") + stderr = err.decode("utf-8", errors="replace") + return CodeExecutionResult( + stdout=stdout, + stderr=stderr, + output_files=[], + ) + + def copy_to_container( + self, + local_path: pathlib.Path, + container_path: str, + ) -> None: + """Copy a local directory into the container via put_archive.""" + if self._container is None: + raise RuntimeError("Container not started") + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w") as tar: + tar.add(str(local_path), arcname=".") + buf.seek(0) + self._container.put_archive(container_path, buf) + + def exec_in_container( + self, + cmd: list[str], + workdir: str = "/root", + timeout: float | None = None, + ) -> tuple[int, str]: + """Run an arbitrary command inside the container. + + Returns (exit_code, combined_output). + """ + if self._container is None: + raise RuntimeError("Container not started") + try: + rc, out, err = self._exec_run_with_timeout( + cmd, + workdir=workdir, + timeout=timeout, + ) + except TimeoutError: + return -1, f"Command timed out after {timeout or self._cmd_timeout}s" + stdout = out.decode("utf-8", errors="replace") + stderr = err.decode("utf-8", errors="replace") + combined = stdout + if stderr: + combined = combined + "\n" + stderr if combined else stderr + return rc, combined + + async def async_exec_in_container( + self, + cmd: list[str], + workdir: str = "/root", + timeout: float | None = None, + ) -> tuple[int, str]: + """Async version of exec_in_container. + + Runs the blocking Docker exec_run in a thread executor so + the asyncio event loop stays free for timeout checks. + """ + timeout = timeout or self._cmd_timeout + + def _blocking(): + if self._container is None: + raise RuntimeError("Container not started") + rc, output = self._container.exec_run( + cmd, + workdir=workdir, + demux=True, + ) + out = (output[0] or b"").decode("utf-8", errors="replace") + err = (output[1] or b"").decode("utf-8", errors="replace") + combined = out + if err: + combined = combined + "\n" + err if combined else err + return rc, combined + + loop = asyncio.get_running_loop() + try: + return await asyncio.wait_for( + loop.run_in_executor(None, _blocking), + timeout=timeout, + ) + except asyncio.TimeoutError: + return -1, f"Command timed out after {timeout}s" + + def read_file_from_container(self, path: str) -> str | None: + """Read a single file from the container, or None.""" + if self._container is None: + return None + try: + bits, _ = self._container.get_archive(path) + buf = io.BytesIO() + for chunk in bits: + buf.write(chunk) + buf.seek(0) + with tarfile.open(fileobj=buf, mode="r") as tar: + for member in tar.getmembers(): + if member.isfile(): + f = tar.extractfile(member) + if f: + return f.read().decode("utf-8", errors="replace") + except Exception: + return None + return None + + def stop(self) -> None: + """Stop and remove the container.""" + if self._container is not None: + try: + self._container.stop(timeout=5) + except Exception: + pass + try: + self._container.remove(force=True) + except Exception: + pass + self._container = None + + +# ── Docker image builder ───────────────────────────────────────────── + + +def build_task_image( + task_dir: pathlib.Path, + client: docker.DockerClient, + *, + rebuild: bool = False, + build_timeout: float = _DEFAULT_BUILD_TIMEOUT, + max_retries: int = 2, +) -> str: + """Build (or reuse) a Docker image for one task. + + Retries up to *max_retries* times on failure, running + ``docker system prune -f`` between attempts to free + build cache and disk space. + + Returns the image tag. + """ + tag = f"skillsbench-{task_dir.name}:latest" + if not rebuild: + try: + client.images.get(tag) + return tag + except docker.errors.ImageNotFound: + pass + + build_ctx = task_dir / "environment" + if not (build_ctx / "Dockerfile").exists(): + raise FileNotFoundError(f"No Dockerfile in {build_ctx}") + + last_exc: Exception | None = None + for attempt in range(1, max_retries + 2): # 1 try + max_retries + try: + logger.info("Building image %s (attempt %d) …", tag, attempt) + client.images.build( + path=str(build_ctx), + tag=tag, + rm=True, + forcerm=True, + timeout=int(build_timeout), + ) + return tag + except Exception as exc: + last_exc = exc + if attempt <= max_retries: + logger.warning( + "Build attempt %d failed for %s: %s — pruning and retrying", + attempt, + tag, + str(exc)[:120], + ) + try: + client.containers.prune() + client.images.prune(filters={"dangling": True}) + except Exception: + pass + else: + break + + raise last_exc # type: ignore[misc] + + +# ── Lenient skill loader ───────────────────────────────────────────── + + +def _load_skill_lenient(skill_dir: pathlib.Path) -> Skill | None: + """Load a skill, falling back to lenient parsing on failure. + + Tries the strict ``load_skill_from_dir`` first. On any error, + manually parses SKILL.md, fixes the frontmatter fields, and + builds a ``Skill`` directly. + + Returns None only for truly unrecoverable cases (no SKILL.md, + unparseable YAML, no description). + """ + # ── strict path ── + try: + return load_skill_from_dir(skill_dir) + except Exception: + pass + + # ── lenient path ── + skill_md = None + for name in ("SKILL.md", "skill.md"): + p = skill_dir / name + if p.exists(): + skill_md = p + break + if skill_md is None: + return None + + try: + content = skill_md.read_text(encoding="utf-8") + except Exception: + return None + + if not content.startswith("---"): + return None + + parts = content.split("---", 2) + if len(parts) < 3: + return None + + try: + parsed = yaml.safe_load(parts[1]) + except yaml.YAMLError: + return None + + if not isinstance(parsed, dict): + return None + + body = parts[2].strip() + + # Fix name: slugify and force to match dir name + parsed["name"] = _slugify(skill_dir.name) + + # Fix allowed-tools: list → comma-separated string + for key in ("allowed-tools", "allowed_tools"): + val = parsed.get(key) + if isinstance(val, list): + parsed[key] = ", ".join(str(v) for v in val) + + # Fix compatibility: dict → JSON string + if isinstance(parsed.get("compatibility"), dict): + parsed["compatibility"] = json.dumps(parsed["compatibility"]) + + # Fix metadata values: ensure all are strings + meta = parsed.get("metadata") + if isinstance(meta, dict): + parsed["metadata"] = { + str(k): str(v) if not isinstance(v, str) else v for k, v in meta.items() + } + + # Ensure description exists + if not parsed.get("description"): + parsed["description"] = f"Skill from {skill_dir.name}" + + try: + frontmatter = Frontmatter.model_validate(parsed) + except Exception: + return None + + # Load resources + references = _load_dir(skill_dir / "references") + assets = _load_dir(skill_dir / "assets") + raw_scripts = _load_dir(skill_dir / "scripts") + scripts = {n: Script(src=c) for n, c in raw_scripts.items()} + resources = Resources( + references=references, + assets=assets, + scripts=scripts, + ) + + return Skill( + frontmatter=frontmatter, + instructions=body, + resources=resources, + ) + + +def load_task_skills( + task_dir: pathlib.Path, +) -> tuple[list[Skill], list[str]]: + """Load all skills from a task's environment/skills/. + + Uses lenient loading to handle malformed frontmatter. + + Returns: + (loaded_skills, error_messages) + """ + skills_dir = task_dir / "environment" / "skills" + if not skills_dir.exists() or not skills_dir.is_dir(): + return [], ["No environment/skills/ directory found"] + + skills: list[Skill] = [] + errors: list[str] = [] + for sd in sorted(skills_dir.iterdir()): + if not sd.is_dir(): + continue + skill = _load_skill_lenient(sd) + if skill is not None: + skills.append(skill) + else: + errors.append(f"{sd.name}: could not load") + return skills, errors + + +# ── task.toml parser ───────────────────────────────────────────────── + + +def parse_task_config( + task_dir: pathlib.Path, +) -> dict[str, float]: + """Read task.toml and return timeout values. + + Returns dict with keys: agent_timeout, build_timeout, + verifier_timeout. + """ + toml_path = task_dir / "task.toml" + defaults = { + "agent_timeout": _DEFAULT_AGENT_TIMEOUT, + "build_timeout": _DEFAULT_BUILD_TIMEOUT, + "verifier_timeout": _DEFAULT_VERIFIER_TIMEOUT, + } + if not toml_path.exists(): + return defaults + + try: + with open(toml_path, "rb") as f: + cfg = tomllib.load(f) + except Exception: + return defaults + + agent_sec = cfg.get("agent", {}) + env_sec = cfg.get("environment", {}) + ver_sec = cfg.get("verifier", {}) + + return { + "agent_timeout": float( + agent_sec.get("timeout_sec", defaults["agent_timeout"]) + ), + "build_timeout": float( + env_sec.get("build_timeout_sec", defaults["build_timeout"]) + ), + "verifier_timeout": float( + ver_sec.get("timeout_sec", defaults["verifier_timeout"]) + ), + } + + +# ── scoring ────────────────────────────────────────────────────────── + + +def score_task_in_container( + executor: TaskContainerExecutor, + task_dir: pathlib.Path, +) -> int: + """Run the real pytest tests inside the container. + + 1. Copy task_dir/tests/ into /tests/ in the container. + 2. Run ``bash /tests/test.sh``. + 3. Read /logs/verifier/reward.txt — ``1`` = PASS. + + Returns 1 (pass) or 0 (fail). + """ + tests_dir = task_dir / "tests" + if not tests_dir.exists(): + logger.warning("No tests/ directory for %s", task_dir.name) + return 0 + + # Ensure /tests/ directory exists in container + executor.exec_in_container(["mkdir", "-p", "/tests"]) + + # Copy tests into container + executor.copy_to_container(tests_dir, "/tests") + + # Make test.sh executable + executor.exec_in_container(["chmod", "+x", "/tests/test.sh"]) + + # Run test.sh (longer timeout — installs deps + runs pytest) + rc, output = executor.exec_in_container( + ["bash", "/tests/test.sh"], + workdir="/root", + timeout=900.0, + ) + logger.debug( + "test.sh for %s exited %d:\n%s", + task_dir.name, + rc, + output[:2000], + ) + + # Read reward + reward = executor.read_file_from_container("/logs/verifier/reward.txt") + if reward is not None and reward.strip() == "1": + return 1 + return 0 + + +def score_task_heuristic( + actual_invocations: list[Invocation], +) -> int: + """Heuristic fallback (--skip-tests mode). + + Passes if the agent loaded a skill, used it, and + produced a final response. + """ + tool_names: list[str] = [] + for inv in actual_invocations: + for tc in get_all_tool_calls(inv.intermediate_data): + tool_names.append(tc.name) + + has_load = "load_skill" in tool_names + has_use = ( + "run_skill_script" in tool_names + or "load_skill_resource" in tool_names + ) + has_response = False + for inv in actual_invocations: + if inv.final_response and inv.final_response.parts: + for part in inv.final_response.parts: + if part.text: + has_response = True + break + if has_response: + break + + return 1 if (has_load and has_use and has_response) else 0 + + +# ── container bash tool ─────────────────────────────────────────── + + +class ContainerBashTool(BaseTool): + """Simple bash tool that runs commands inside the task container.""" + + def __init__(self, executor: TaskContainerExecutor): + super().__init__( + name="bash", + description=( + "Run a bash command inside the task environment." + " Use this to read files, write files, install" + " packages, or run arbitrary shell commands." + ), + ) + self._executor = executor + + def _get_declaration(self) -> genai_types.FunctionDeclaration | None: + return genai_types.FunctionDeclaration( + name=self.name, + description=self.description, + parameters_json_schema={ + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The bash command to execute.", + }, + }, + "required": ["command"], + }, + ) + + async def run_async(self, *, args, tool_context) -> Any: + command = args.get("command", "") + if not command: + return {"error": "command is required"} + # Use async exec to keep the event loop free for timeouts + rc, output = await self._executor.async_exec_in_container( + ["bash", "-c", command], + ) + # Truncate very long output to avoid blowing context + if len(output) > 10000: + output = output[:10000] + "\n... (truncated)" + return { + "exit_code": rc, + "output": output, + } + + +# ── agent builder ──────────────────────────────────────────────────── + + +def build_agent( + skills: list[Skill], + executor: TaskContainerExecutor, +) -> Agent: + """Create a fresh agent with the given skills.""" + toolset = SkillToolset( + skills=skills, + code_executor=executor, + ) + bash_tool = ContainerBashTool(executor) + model = Gemini( + model=_MODEL_NAME, + retry_options=genai_types.HttpRetryOptions( + attempts=5, + initialDelay=2.0, + maxDelay=60.0, + expBase=2.0, + httpStatusCodes=[429, 503], + ), + ) + return Agent( + model=model, + name="skillsbench_agent", + description=( + "An agent that completes tasks by discovering and using" + " available skills from the SkillsBench benchmark." + ), + instruction=( + "You are an agent that completes tasks by discovering" + " and using available skills. Follow this workflow:\n" + "1. Use list_skills to find relevant skills.\n" + "2. Use load_skill to read the skill's instructions" + " carefully.\n" + "3. Use load_skill_resource to examine references or" + " sample data if available.\n" + "4. Use run_skill_script to run the skill's" + " scripts with appropriate arguments.\n" + "5. Use bash to read/write files, install packages," + " or run any shell command in the environment.\n" + "6. Write the required output files and present a" + " clear answer.\n" + "\nAlways check skill instructions before executing" + " scripts." + ), + generate_content_config=genai_types.GenerateContentConfig( + temperature=1.0, + thinking_config=genai_types.ThinkingConfig( + thinking_level="HIGH", + ), + ), + tools=[toolset, bash_tool], + ) + + +# ── agent runner ───────────────────────────────────────────────────── + + +async def run_task( + agent: Agent, + user_query: str, +) -> list[Invocation]: + """Run a single task and return invocations.""" + session_service = InMemorySessionService() + artifact_service = InMemoryArtifactService() + memory_service = InMemoryMemoryService() + + app_name = "skillsbench_full_eval" + user_id = "eval_user" + session_id = str(uuid.uuid4()) + + await session_service.create_session( + app_name=app_name, + user_id=user_id, + state={}, + session_id=session_id, + ) + + user_content = genai_types.Content( + role="user", + parts=[genai_types.Part.from_text(text=user_query)], + ) + + async with Runner( + app_name=app_name, + agent=agent, + artifact_service=artifact_service, + session_service=session_service, + memory_service=memory_service, + ) as runner: + events: list[Event] = [] + async with Aclosing( + runner.run_async( + user_id=user_id, + session_id=session_id, + new_message=user_content, + ) + ) as agen: + invocation_id = None + async for event in agen: + if not invocation_id: + invocation_id = event.invocation_id + events.append( + Event( + content=user_content, + author="user", + invocation_id=invocation_id, + ) + ) + events.append(event) + + return EvaluationGenerator.convert_events_to_eval_invocations(events) + + +# ── task result ────────────────────────────────────────────────────── + + +class TaskResult: + """Result of a single task evaluation.""" + + def __init__( + self, + task_name: str, + score: int, + num_skills: int, + elapsed: float, + error: str | None = None, + ): + self.task_name = task_name + self.score = score + self.num_skills = num_skills + self.elapsed = elapsed + self.error = error + + +# ── task discovery ─────────────────────────────────────────────────── + + +def discover_tasks( + tasks_dir: pathlib.Path, + filter_pattern: str | None = None, +) -> list[pathlib.Path]: + """Find task directories containing instruction.md.""" + tasks = [] + for d in sorted(tasks_dir.iterdir()): + if not d.is_dir(): + continue + if not (d / "instruction.md").exists(): + continue + if filter_pattern and filter_pattern not in d.name: + continue + tasks.append(d) + return tasks + + +# ── evaluate one task ──────────────────────────────────────────────── + + +def _watchdog_stop(executor: TaskContainerExecutor, seconds: float): + """Background thread: force-kill the container after *seconds*. + + This is a hard safety net — if asyncio.wait_for fails to cancel + a task because the event loop is blocked by synchronous Docker + calls, the watchdog kills the container from a separate thread, + causing the blocking exec_run to fail and unblock the loop. + """ + time.sleep(seconds) + try: + executor.stop() + except Exception: + pass + + +async def evaluate_task( + task_dir: pathlib.Path, + client: docker.DockerClient, + *, + timeout_override: float | None = None, + rebuild: bool = False, + skip_tests: bool = False, +) -> TaskResult: + """Evaluate a single SkillsBench task end-to-end. + + 1. Parse task.toml for timeouts + 2. Build Docker image (or use cached) + 3. Load skills with lenient loader + 4. Start TaskContainerExecutor + 5. Build Agent with SkillToolset + 6. Run agent with instruction.md + 7. Run tests inside same container (or heuristic) + 8. Stop container + """ + task_name = task_dir.name + start = time.time() + executor = TaskContainerExecutor() + num_skills = 0 + agent_timeout = _DEFAULT_AGENT_TIMEOUT + watchdog = None + + try: + # 1. Parse config + config = parse_task_config(task_dir) + agent_timeout = timeout_override or config["agent_timeout"] + + # 2. Build image + try: + image_tag = build_task_image( + task_dir, + client, + rebuild=rebuild, + build_timeout=config["build_timeout"], + ) + except Exception as exc: + return TaskResult( + task_name=task_name, + score=0, + num_skills=0, + elapsed=time.time() - start, + error=f"image build: {str(exc)[:100]}", + ) + + # 3. Load instruction + try: + user_query = ( + (task_dir / "instruction.md").read_text(encoding="utf-8").strip() + ) + except Exception as exc: + return TaskResult( + task_name=task_name, + score=0, + num_skills=0, + elapsed=time.time() - start, + error=f"instruction.md: {exc}", + ) + + # 4. Load skills + skills, skill_errors = load_task_skills(task_dir) + num_skills = len(skills) + if not skills: + msg = "; ".join(skill_errors) if skill_errors else "No skills" + return TaskResult( + task_name=task_name, + score=0, + num_skills=0, + elapsed=time.time() - start, + error=f"skills: {msg}", + ) + + # 5. Start container + executor.start(image_tag, client) + + # 6. Start watchdog — hard kill after agent_timeout + 60s + watchdog = threading.Thread( + target=_watchdog_stop, + args=(executor, agent_timeout + 60), + daemon=True, + ) + watchdog.start() + + # 7. Build agent and run + agent = build_agent(skills, executor) + invocations = await asyncio.wait_for( + run_task(agent, user_query), + timeout=agent_timeout, + ) + + # 8. Score + if skip_tests: + score = score_task_heuristic(invocations) + else: + score = score_task_in_container(executor, task_dir) + + return TaskResult( + task_name=task_name, + score=score, + num_skills=num_skills, + elapsed=time.time() - start, + ) + + except Exception as exc: + # Score container tests even on error — the agent + # may have produced partial output files. + score = 0 + if not skip_tests and executor._container is not None: + try: + score = score_task_in_container(executor, task_dir) + except Exception: + pass + is_timeout = isinstance(exc, asyncio.TimeoutError) + err_msg = f"timeout ({agent_timeout}s)" if is_timeout else str(exc)[:120] + return TaskResult( + task_name=task_name, + score=score, + num_skills=num_skills, + elapsed=time.time() - start, + error=err_msg, + ) + finally: + executor.stop() + + +# ── printing ───────────────────────────────────────────────────────── + + +def print_header(): + print() + print("=" * 60) + print(" SkillsBench Full Evaluation — Docker + Pytest") + print("=" * 60) + print() + + +def print_task_result( + idx: int, + total: int, + result: TaskResult, +): + mark = "PASS" if result.score == 1 else "FAIL" + name = result.task_name[:35].ljust(35) + if result.error: + detail = f"({result.error})" + else: + detail = f"({result.num_skills} skills, {result.elapsed:.1f}s)" + print(f"[{idx:>2}/{total}] {name} {mark} {detail}") + sys.stdout.flush() + + +def print_summary( + results: list[TaskResult], + total_tasks: int, + elapsed: float, +): + passed = sum(1 for r in results if r.score == 1) + loadable = sum(1 for r in results if r.num_skills > 0) + times = [r.elapsed for r in results if r.error != "timeout"] + avg_time = sum(times) / max(len(times), 1) + pct = (passed / max(total_tasks, 1)) * 100 + + print() + print("=" * 60) + print(" Leaderboard Summary") + print("=" * 60) + print(f" Model: {_MODEL_NAME}") + print(f" Framework: ADK SkillToolset (Docker)") + print(f" Score: {passed}/{total_tasks} ({pct:.1f}%)") + print(f" Loadable tasks: {loadable}/{total_tasks}") + print(f" Avg time/task: {avg_time:.1f}s") + print(f" Total elapsed: {elapsed:.0f}s") + print("=" * 60) + + +# ── full evaluation loop ───────────────────────────────────────────── + + +def _docker_prune(client: docker.DockerClient) -> None: + """Prune stopped containers and dangling images.""" + try: + client.containers.prune() + client.images.prune(filters={"dangling": True}) + logger.info("Docker prune completed") + except Exception as exc: + logger.warning("Docker prune failed: %s", exc) + + +async def run_full_evaluation( + tasks_dir: pathlib.Path, + client: docker.DockerClient, + *, + timeout_override: float | None = None, + filter_pattern: str | None = None, + rebuild: bool = False, + build_only: bool = False, + skip_tests: bool = False, + prune_interval: int = 20, +) -> list[TaskResult]: + """Run evaluation on all matching tasks. + + Args: + prune_interval: Prune Docker every N tasks to prevent + disk buildup during long runs. Set to 0 to disable. + """ + task_dirs = discover_tasks(tasks_dir, filter_pattern) + total = len(task_dirs) + print(f"Found {total} tasks in {tasks_dir}\n") + + if build_only: + ok = 0 + fail = 0 + for idx, td in enumerate(task_dirs, 1): + name = td.name[:35].ljust(35) + try: + config = parse_task_config(td) + tag = build_task_image( + td, + client, + rebuild=rebuild, + build_timeout=config["build_timeout"], + ) + ok += 1 + print(f"[{idx:>2}/{total}] {name} OK ({tag})") + except Exception as exc: + fail += 1 + print(f"[{idx:>2}/{total}] {name} FAIL ({str(exc)[:80]})") + sys.stdout.flush() + # Periodic prune during build-only runs + if prune_interval and idx % prune_interval == 0: + print(f" >> pruning Docker (every {prune_interval})") + _docker_prune(client) + print(f"\nBuild summary: {ok} OK, {fail} FAIL / {total}") + return [] + + results: list[TaskResult] = [] + for idx, td in enumerate(task_dirs, 1): + name = td.name[:35].ljust(35) + print( + f"[{idx:>2}/{total}] {name} ...running", + end="", + flush=True, + ) + result = await evaluate_task( + td, + client, + timeout_override=timeout_override, + rebuild=rebuild, + skip_tests=skip_tests, + ) + results.append(result) + # Overwrite the "...running" line with final result + print(f"\r", end="") + print_task_result(idx, total, result) + # Periodic prune to prevent disk buildup + if prune_interval and idx % prune_interval == 0: + print(f" >> pruning Docker (every {prune_interval})") + _docker_prune(client) + + return results + + +# ── CLI ────────────────────────────────────────────────────────────── + + +def main(): + parser = argparse.ArgumentParser( + description="SkillsBench Docker-based evaluation runner", + ) + parser.add_argument( + "--tasks-dir", + type=pathlib.Path, + default=_DEFAULT_TASKS_DIR, + help=( + "Path to SkillsBench tasks directory" + " (default: /tmp/skillsbench/tasks)" + ), + ) + parser.add_argument( + "--timeout", + type=float, + default=None, + help="Override per-task agent timeout in seconds", + ) + parser.add_argument( + "--filter", + type=str, + default=None, + help="Only run tasks whose name contains PATTERN", + ) + parser.add_argument( + "--rebuild", + action="store_true", + help="Force Docker image rebuild", + ) + parser.add_argument( + "--build-only", + action="store_true", + help="Build Docker images only, don't run agents", + ) + parser.add_argument( + "--skip-tests", + action="store_true", + help="Use tool-call heuristic instead of pytest scoring", + ) + parser.add_argument( + "--prune-interval", + type=int, + default=20, + help=( + "Prune Docker every N tasks to prevent disk buildup" + " (default: 20, 0 to disable)" + ), + ) + args = parser.parse_args() + + logging.basicConfig(level=logging.WARNING) + + print_header() + + # Prereq check + client = ensure_docker_running() + + start = time.time() + results = asyncio.run( + run_full_evaluation( + tasks_dir=args.tasks_dir, + client=client, + timeout_override=args.timeout, + filter_pattern=args.filter, + rebuild=args.rebuild, + build_only=args.build_only, + skip_tests=args.skip_tests, + prune_interval=args.prune_interval, + ) + ) + elapsed = time.time() - start + + if results: + print_summary(results, len(results), elapsed) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillsbench/metrics.py b/benchmarks/skillsbench/metrics.py new file mode 100644 index 0000000000..8477d9f42e --- /dev/null +++ b/benchmarks/skillsbench/metrics.py @@ -0,0 +1,226 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Custom metrics for SkillsBench evaluation. + +These metrics follow the ADK custom metric function signature: + + def metric_fn( + eval_metric: EvalMetric, + actual_invocations: list[Invocation], + expected_invocations: Optional[list[Invocation]], + conversation_scenario: Optional[ConversationScenario] = None, + ) -> EvaluationResult + +They can be referenced in eval configs via their dotted path, e.g.: + "benchmarks.skillsbench.metrics.skill_discovery_score" +""" + +from __future__ import annotations + +from typing import Optional + +from google.adk.evaluation.eval_case import ConversationScenario +from google.adk.evaluation.eval_case import get_all_tool_calls +from google.adk.evaluation.eval_case import Invocation +from google.adk.evaluation.eval_metrics import EvalMetric +from google.adk.evaluation.eval_metrics import EvalStatus +from google.adk.evaluation.evaluator import EvaluationResult +from google.adk.evaluation.evaluator import PerInvocationResult + + +def _get_tool_names_from_invocations( + invocations: list[Invocation], +) -> list[str]: + """Extract all tool call names from a list of invocations.""" + names = [] + for inv in invocations: + for tool_call in get_all_tool_calls(inv.intermediate_data): + names.append(tool_call.name) + return names + + +def skill_discovery_score( + eval_metric: EvalMetric, + actual_invocations: list[Invocation], + expected_invocations: Optional[list[Invocation]], + conversation_scenario: Optional[ConversationScenario] = None, +) -> EvaluationResult: + """Score 1.0 if the agent called both list_skills and load_skill. + + This metric checks whether the agent properly discovered skills + before attempting to use them, which is the expected workflow for + SkillsBench tasks. + """ + tool_names = _get_tool_names_from_invocations(actual_invocations) + called_list = any(name == "list_skills" for name in tool_names) + called_load = any(name == "load_skill" for name in tool_names) + + score = 1.0 if (called_list and called_load) else 0.0 + status = EvalStatus.PASSED if score >= 1.0 else EvalStatus.FAILED + + per_invocation = [] + for i, actual in enumerate(actual_invocations): + expected = None + if expected_invocations and i < len(expected_invocations): + expected = expected_invocations[i] + per_invocation.append( + PerInvocationResult( + actual_invocation=actual, + expected_invocation=expected, + score=score, + eval_status=status, + ) + ) + + return EvaluationResult( + overall_score=score, + overall_eval_status=status, + per_invocation_results=per_invocation, + ) + + +def tool_usage_score( + eval_metric: EvalMetric, + actual_invocations: list[Invocation], + expected_invocations: Optional[list[Invocation]], + conversation_scenario: Optional[ConversationScenario] = None, +) -> EvaluationResult: + """Fraction of expected tool calls that were actually made. + + Compares the set of tool names in expected_invocations against + actual_invocations. Score is |expected ∩ actual| / |expected|. + Uses ANY_ORDER matching — only checks that expected tools were + called, regardless of order or extra calls. + """ + if not expected_invocations: + return EvaluationResult( + overall_score=1.0, + overall_eval_status=EvalStatus.PASSED, + ) + + expected_names = set(_get_tool_names_from_invocations(expected_invocations)) + actual_names = set(_get_tool_names_from_invocations(actual_invocations)) + + if not expected_names: + score = 1.0 + else: + matched = expected_names & actual_names + score = len(matched) / len(expected_names) + + status = EvalStatus.PASSED if score >= 0.5 else EvalStatus.FAILED + + per_invocation = [] + for i, actual in enumerate(actual_invocations): + expected = None + if expected_invocations and i < len(expected_invocations): + expected = expected_invocations[i] + per_invocation.append( + PerInvocationResult( + actual_invocation=actual, + expected_invocation=expected, + score=score, + eval_status=status, + ) + ) + + return EvaluationResult( + overall_score=score, + overall_eval_status=status, + per_invocation_results=per_invocation, + ) + + +def skillsbench_binary_score( + eval_metric: EvalMetric, + actual_invocations: list[Invocation], + expected_invocations: Optional[list[Invocation]], + conversation_scenario: Optional[ConversationScenario] = None, +) -> EvaluationResult: + """Binary pass/fail: 1.0 if final response contains expected text. + + Mirrors the SkillsBench binary scoring methodology. Checks whether + key strings from the expected final response appear in the actual + final response. The match is case-insensitive and checks for + substring containment of each non-empty line in the reference. + """ + if not expected_invocations or not actual_invocations: + return EvaluationResult( + overall_score=0.0, + overall_eval_status=EvalStatus.NOT_EVALUATED, + ) + + # Get the last actual response text + actual_text = "" + for inv in reversed(actual_invocations): + if inv.final_response and inv.final_response.parts: + for part in inv.final_response.parts: + if part.text: + actual_text = part.text + break + if actual_text: + break + + # Get the expected response text + expected_text = "" + for inv in reversed(expected_invocations): + if inv.final_response and inv.final_response.parts: + for part in inv.final_response.parts: + if part.text: + expected_text = part.text + break + if expected_text: + break + + if not expected_text: + return EvaluationResult( + overall_score=0.0, + overall_eval_status=EvalStatus.NOT_EVALUATED, + ) + + # Check that each non-empty reference line appears in the actual + reference_lines = [ + line.strip() for line in expected_text.split("\n") if line.strip() + ] + actual_lower = actual_text.lower() + matched = sum(1 for line in reference_lines if line.lower() in actual_lower) + score = ( + 1.0 + if matched == len(reference_lines) + else matched / max(len(reference_lines), 1) + ) + + # Binary: pass only if all reference lines matched + is_pass = matched == len(reference_lines) and len(reference_lines) > 0 + status = EvalStatus.PASSED if is_pass else EvalStatus.FAILED + + per_invocation = [] + for i, actual in enumerate(actual_invocations): + expected = None + if expected_invocations and i < len(expected_invocations): + expected = expected_invocations[i] + per_invocation.append( + PerInvocationResult( + actual_invocation=actual, + expected_invocation=expected, + score=1.0 if is_pass else 0.0, + eval_status=status, + ) + ) + + return EvaluationResult( + overall_score=1.0 if is_pass else 0.0, + overall_eval_status=status, + per_invocation_results=per_invocation, + ) diff --git a/benchmarks/skillsbench/runner.py b/benchmarks/skillsbench/runner.py new file mode 100644 index 0000000000..8d6d547613 --- /dev/null +++ b/benchmarks/skillsbench/runner.py @@ -0,0 +1,313 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Standalone SkillsBench runner that produces leaderboard-compatible scores. + +Usage: + python benchmarks/skillsbench/runner.py + python benchmarks/skillsbench/runner.py --num-runs 3 + python benchmarks/skillsbench/runner.py --eval-set path/to/eval.json + +Environment variables: + GOOGLE_API_KEY — API key for authentication + GOOGLE_GENAI_USE_VERTEXAI — Set to 1 for Vertex AI backend + +This script: +1. Loads the SkillsBench agent and eval set +2. Runs each task through the ADK Runner directly +3. Applies all 3 custom metrics (discovery, tool usage, binary) +4. Outputs per-task results and a leaderboard-format summary +""" + +from __future__ import annotations + +import argparse +import asyncio +import json +import logging +import pathlib +import sys +import time +import uuid +from typing import Optional + +from google.adk.evaluation.eval_case import Invocation +from google.adk.evaluation.eval_metrics import EvalMetric +from google.adk.evaluation.eval_set import EvalSet +from google.adk.evaluation.evaluation_generator import EvaluationGenerator +from google.adk.runners import Runner +from google.adk.sessions.in_memory_session_service import InMemorySessionService +from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService +from google.adk.memory.in_memory_memory_service import InMemoryMemoryService +from google.adk.utils.context_utils import Aclosing +from google.genai import types as genai_types + +from .metrics import ( + skill_discovery_score, + skillsbench_binary_score, + tool_usage_score, +) + +logger = logging.getLogger(__name__) + +_BENCHMARKS_DIR = pathlib.Path(__file__).parent +_DEFAULT_EVAL_SET = _BENCHMARKS_DIR / "eval_sets" / "skillsbench_eval.json" +_MODEL_NAME = "gemini-3-flash-preview" + + +def load_eval_set(path: pathlib.Path) -> EvalSet: + """Load an EvalSet from a JSON file.""" + with open(path) as f: + data = json.load(f) + return EvalSet.model_validate(data) + + +def print_header(): + """Print the SkillsBench header.""" + print() + print("=" * 60) + print(" SkillsBench Evaluation — ADK SkillToolset") + print("=" * 60) + print() + + +def print_results_table(results: dict[str, dict[str, float]]): + """Print per-task results as a formatted table.""" + print(f"{'Task':<45} {'Discovery':>9} {'Tools':>7} {'Pass':>6}") + print("-" * 70) + for task_id, scores in results.items(): + short_id = task_id[:44] + disc = scores.get("skill_discovery", 0.0) + tools = scores.get("tool_usage", 0.0) + binary = scores.get("binary_pass", 0.0) + mark = "PASS" if binary >= 1.0 else "FAIL" + print(f"{short_id:<45} {disc:>8.1f} {tools:>7.2f} {mark:>6}") + print("-" * 70) + + +def print_leaderboard_summary( + results: dict[str, dict[str, float]], + num_tasks: int, + elapsed: float, +): + """Print a leaderboard-format summary.""" + passed = sum( + 1 for scores in results.values() if scores.get("binary_pass", 0.0) >= 1.0 + ) + avg_discovery = sum( + s.get("skill_discovery", 0.0) for s in results.values() + ) / max(len(results), 1) + avg_tools = sum(s.get("tool_usage", 0.0) for s in results.values()) / max( + len(results), 1 + ) + pct = (passed / max(num_tasks, 1)) * 100 + + print() + print("=" * 60) + print(" Leaderboard Summary") + print("=" * 60) + print(f" Model: {_MODEL_NAME}") + print(f" Framework: ADK SkillToolset") + print(f" Tasks: {passed}/{num_tasks} ({pct:.1f}%)") + print(f" Avg Discovery: {avg_discovery:.2f}") + print(f" Avg Tool Usage: {avg_tools:.2f}") + print(f" Elapsed: {elapsed:.1f}s") + print("=" * 60) + + +async def run_single_eval_case( + root_agent, + eval_case, +) -> list[Invocation]: + """Run a single eval case through the Runner and return invocations.""" + session_service = InMemorySessionService() + artifact_service = InMemoryArtifactService() + memory_service = InMemoryMemoryService() + + app_name = "skillsbench_eval" + user_id = "eval_user" + session_id = str(uuid.uuid4()) + + await session_service.create_session( + app_name=app_name, + user_id=user_id, + state={}, + session_id=session_id, + ) + + async with Runner( + app_name=app_name, + agent=root_agent, + artifact_service=artifact_service, + session_service=session_service, + memory_service=memory_service, + ) as runner: + events = [] + for invocation in eval_case.conversation: + user_content = invocation.user_content + + async with Aclosing( + runner.run_async( + user_id=user_id, + session_id=session_id, + new_message=user_content, + ) + ) as agen: + invocation_id = None + async for event in agen: + if not invocation_id: + invocation_id = event.invocation_id + from google.adk.events.event import Event + + events.append( + Event( + content=user_content, + author="user", + invocation_id=invocation_id, + ) + ) + events.append(event) + + return EvaluationGenerator.convert_events_to_eval_invocations(events) + + +def score_invocations( + actual_invocations: list[Invocation], + expected_invocations: Optional[list[Invocation]], +) -> dict[str, float]: + """Apply all 3 metrics and return scores.""" + metric = EvalMetric(metric_name="skillsbench") + scores = {} + + result = skill_discovery_score( + metric, actual_invocations, expected_invocations + ) + scores["skill_discovery"] = result.overall_score or 0.0 + + result = tool_usage_score(metric, actual_invocations, expected_invocations) + scores["tool_usage"] = result.overall_score or 0.0 + + result = skillsbench_binary_score( + metric, actual_invocations, expected_invocations + ) + scores["binary_pass"] = result.overall_score or 0.0 + + return scores + + +async def run_evaluation( + eval_set_path: Optional[pathlib.Path] = None, + num_runs: int = 1, +) -> dict[str, dict[str, float]]: + """Run the full SkillsBench evaluation.""" + path = eval_set_path or _DEFAULT_EVAL_SET + eval_set = load_eval_set(path) + + # Import agent (triggers skill loading) + from .agent import root_agent + + results: dict[str, dict[str, float]] = {} + total = len(eval_set.eval_cases) + + for idx, eval_case in enumerate(eval_set.eval_cases, 1): + eval_id = eval_case.eval_id + print(f"\n[{idx}/{total}] Running: {eval_id}") + + run_scores: list[dict[str, float]] = [] + for run in range(num_runs): + if num_runs > 1: + print(f" Run {run + 1}/{num_runs}...") + + try: + actual_invocations = await run_single_eval_case(root_agent, eval_case) + + # Print what the agent did + for inv in actual_invocations: + if inv.final_response and inv.final_response.parts: + for part in inv.final_response.parts: + if part.text: + preview = part.text[:200].replace("\n", " ") + print(f" Response: {preview}...") + break + + expected_invocations = eval_case.conversation + scores = score_invocations(actual_invocations, expected_invocations) + run_scores.append(scores) + + disc = scores["skill_discovery"] + tools = scores["tool_usage"] + binary = scores["binary_pass"] + mark = "PASS" if binary >= 1.0 else "FAIL" + print(f" Scores: discovery={disc:.1f} tools={tools:.2f} binary={mark}") + + except Exception as e: + logger.error("Error running %s: %s", eval_id, e) + print(f" ERROR: {e}") + run_scores.append({ + "skill_discovery": 0.0, + "tool_usage": 0.0, + "binary_pass": 0.0, + }) + + # Average scores across runs + avg_scores: dict[str, float] = {} + for key in ["skill_discovery", "tool_usage", "binary_pass"]: + values = [s[key] for s in run_scores] + avg_scores[key] = sum(values) / len(values) + results[eval_id] = avg_scores + + return results + + +def main(): + parser = argparse.ArgumentParser( + description="SkillsBench evaluation runner for ADK" + ) + parser.add_argument( + "--eval-set", + type=pathlib.Path, + default=None, + help="Path to eval set JSON (default: built-in)", + ) + parser.add_argument( + "--num-runs", + type=int, + default=1, + help="Number of runs per task (default: 1)", + ) + args = parser.parse_args() + + logging.basicConfig(level=logging.WARNING) + + print_header() + start = time.time() + + results = asyncio.run( + run_evaluation( + eval_set_path=args.eval_set, + num_runs=args.num_runs, + ) + ) + + elapsed = time.time() - start + eval_path = args.eval_set or _DEFAULT_EVAL_SET + eval_set = load_eval_set(eval_path) + + print() + print_results_table(results) + print_leaderboard_summary(results, len(eval_set.eval_cases), elapsed) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillsbench/skills/csv-aggregation/SKILL.md b/benchmarks/skillsbench/skills/csv-aggregation/SKILL.md new file mode 100644 index 0000000000..3d45376adc --- /dev/null +++ b/benchmarks/skillsbench/skills/csv-aggregation/SKILL.md @@ -0,0 +1,41 @@ +--- +name: csv-aggregation +description: Aggregate and summarize CSV data by computing statistics on specified columns. +--- + +# CSV Aggregation Skill + +Analyze CSV data by computing aggregate statistics (sum, mean, min, max, count) grouped by a specified column. + +## Available Scripts + +### `aggregate.py` + +Reads CSV data from stdin and computes aggregate statistics. + +**Usage**: `run_skill_script(skill_name="csv-aggregation", script_path="scripts/aggregate.py", args={"group_col": "department", "metric_col": "salary"})` + +The script expects CSV data piped via stdin or provided as the `data` argument. Pass column names as arguments: +- `group_col`: The column to group by +- `metric_col`: The column to compute statistics on + +**Output format**: +``` +Group: + count: + sum: + mean: + min: + max: +``` + +## References + +- [sample-data.md](./references/sample-data.md) — Sample CSV dataset for testing + +## Workflow + +1. Use `load_skill` to read these instructions. +2. Use `load_skill_resource` to load the sample data reference. +3. Use `run_skill_script` with the appropriate arguments to aggregate the data. +4. Present the aggregated results to the user. diff --git a/benchmarks/skillsbench/skills/csv-aggregation/references/sample-data.md b/benchmarks/skillsbench/skills/csv-aggregation/references/sample-data.md new file mode 100644 index 0000000000..4e2ce51bbc --- /dev/null +++ b/benchmarks/skillsbench/skills/csv-aggregation/references/sample-data.md @@ -0,0 +1,15 @@ +# Sample CSV Data + +Use this data as input for the aggregation script: + +```csv +name,department,salary,years +Alice,Engineering,95000,5 +Bob,Marketing,72000,3 +Carol,Engineering,102000,8 +Dave,Marketing,68000,2 +Eve,Engineering,88000,4 +Frank,Sales,76000,6 +Grace,Sales,81000,7 +Hank,Marketing,74000,4 +``` diff --git a/benchmarks/skillsbench/skills/csv-aggregation/scripts/aggregate.py b/benchmarks/skillsbench/skills/csv-aggregation/scripts/aggregate.py new file mode 100644 index 0000000000..fb073f5539 --- /dev/null +++ b/benchmarks/skillsbench/skills/csv-aggregation/scripts/aggregate.py @@ -0,0 +1,50 @@ +"""Aggregate CSV data by a grouping column.""" + +import csv +import io +import sys + + +def parse_args(args): + params = {} + for arg in args: + if "=" in arg: + key, value = arg.split("=", 1) + params[key] = value + return params + + +def main(): + params = parse_args(sys.argv[1:]) + group_col = params.get("group_col", "department") + metric_col = params.get("metric_col", "salary") + + data = """name,department,salary,years +Alice,Engineering,95000,5 +Bob,Marketing,72000,3 +Carol,Engineering,102000,8 +Dave,Marketing,68000,2 +Eve,Engineering,88000,4 +Frank,Sales,76000,6 +Grace,Sales,81000,7 +Hank,Marketing,74000,4""" + + reader = csv.DictReader(io.StringIO(data)) + groups = {} + for row in reader: + group = row[group_col] + value = float(row[metric_col]) + groups.setdefault(group, []).append(value) + + for group_name in sorted(groups): + values = groups[group_name] + print(f"Group: {group_name}") + print(f" count: {len(values)}") + print(f" sum: {sum(values):.0f}") + print(f" mean: {sum(values) / len(values):.0f}") + print(f" min: {min(values):.0f}") + print(f" max: {max(values):.0f}") + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillsbench/skills/function-scaffold/SKILL.md b/benchmarks/skillsbench/skills/function-scaffold/SKILL.md new file mode 100644 index 0000000000..af0cf27503 --- /dev/null +++ b/benchmarks/skillsbench/skills/function-scaffold/SKILL.md @@ -0,0 +1,30 @@ +--- +name: function-scaffold +description: Generate Python function scaffolds with type hints and docstrings from a specification. +--- + +# Function Scaffold Skill + +Generate Python function stubs from a natural-language specification, including type hints, docstrings, and placeholder implementations. + +## Available Scripts + +### `scaffold.py` + +Generates a Python function scaffold from a specification. + +**Usage**: `run_skill_script(skill_name="function-scaffold", script_path="scripts/scaffold.py", args={"name": "calculate_bmi", "params": "weight:float,height:float", "returns": "float", "description": "Calculate Body Mass Index"})` + +Arguments: +- `name`: Function name (snake_case) +- `params`: Comma-separated parameter list with types (e.g., `x:int,y:str`) +- `returns`: Return type annotation +- `description`: One-line description for the docstring + +**Output format**: Complete Python function with type hints and docstring. + +## Workflow + +1. Use `load_skill` to read these instructions. +2. Use `run_skill_script` with the function specification. +3. Present the generated scaffold to the user. diff --git a/benchmarks/skillsbench/skills/function-scaffold/scripts/scaffold.py b/benchmarks/skillsbench/skills/function-scaffold/scripts/scaffold.py new file mode 100644 index 0000000000..f9df8f2c01 --- /dev/null +++ b/benchmarks/skillsbench/skills/function-scaffold/scripts/scaffold.py @@ -0,0 +1,66 @@ +"""Generate Python function scaffolds from specifications.""" + +import sys + + +def parse_args(args): + params = {} + current_key = None + current_val = [] + for arg in args: + if "=" in arg and not current_key: + key, value = arg.split("=", 1) + if value.startswith("'") and not value.endswith("'"): + current_key = key + current_val = [value[1:]] + elif value.startswith("'") and value.endswith("'"): + params[key] = value[1:-1] + else: + params[key] = value + elif current_key: + if arg.endswith("'"): + current_val.append(arg[:-1]) + params[current_key] = " ".join(current_val) + current_key = None + current_val = [] + else: + current_val.append(arg) + if current_key: + params[current_key] = " ".join(current_val) + return params + + +def main(): + params = parse_args(sys.argv[1:]) + func_name = params.get("name", "my_function") + func_params = params.get("params", "") + returns = params.get("returns", "None") + description = params.get("description", "TODO: Add description") + + param_list = [] + if func_params: + for p in func_params.split(","): + if ":" in p: + pname, ptype = p.split(":", 1) + param_list.append(f"{pname}: {ptype}") + else: + param_list.append(p) + + params_str = ", ".join(param_list) + print(f"def {func_name}({params_str}) -> {returns}:") + print(f' """{description}') + print() + if param_list: + print(" Args:") + for p in param_list: + pname = p.split(":")[0].strip() + print(f" {pname}: TODO") + print() + print(" Returns:") + print(f" {returns}: TODO") + print(' """') + print(" raise NotImplementedError") + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillsbench/skills/html-extraction/SKILL.md b/benchmarks/skillsbench/skills/html-extraction/SKILL.md new file mode 100644 index 0000000000..a8b30edfd1 --- /dev/null +++ b/benchmarks/skillsbench/skills/html-extraction/SKILL.md @@ -0,0 +1,35 @@ +--- +name: html-extraction +description: Extract structured data from HTML content using CSS-like selectors. +--- + +# HTML Extraction Skill + +Parse HTML content and extract text, links, or table data using tag-based selectors. + +## Available Scripts + +### `extract.py` + +Extracts content from embedded sample HTML based on a target selector. + +**Usage**: `run_skill_script(skill_name="html-extraction", script_path="scripts/extract.py", args={"target": "links"})` + +Supported targets: +- `target=links`: Extract all hyperlinks (text and href) +- `target=headings`: Extract all heading text +- `target=table`: Extract table data as CSV +- `target=text`: Extract all visible text content + +**Output format**: One extracted item per line. + +## References + +- [sample-page.md](./references/sample-page.md) — Sample HTML page for testing + +## Workflow + +1. Use `load_skill` to read these instructions. +2. Use `load_skill_resource` to see the sample HTML page. +3. Use `run_skill_script` with the desired target to extract data. +4. Present the extracted content to the user. diff --git a/benchmarks/skillsbench/skills/html-extraction/references/sample-page.md b/benchmarks/skillsbench/skills/html-extraction/references/sample-page.md new file mode 100644 index 0000000000..75e0a58b52 --- /dev/null +++ b/benchmarks/skillsbench/skills/html-extraction/references/sample-page.md @@ -0,0 +1,23 @@ +# Sample HTML Page + +The extraction script processes this embedded HTML: + +```html + +Product Catalog + +

Products

+

Electronics

+ + + + + +
ProductPriceStock
Laptop999.9915
Phone699.9942
Tablet449.9928
+

Links

+ View Laptop + View Phone + View Tablet + + +``` diff --git a/benchmarks/skillsbench/skills/html-extraction/scripts/extract.py b/benchmarks/skillsbench/skills/html-extraction/scripts/extract.py new file mode 100644 index 0000000000..2aab5c48aa --- /dev/null +++ b/benchmarks/skillsbench/skills/html-extraction/scripts/extract.py @@ -0,0 +1,72 @@ +"""Extract structured data from HTML content.""" + +import re +import sys + +SAMPLE_HTML = """ +Product Catalog + +

Products

+

Electronics

+ + + + + +
ProductPriceStock
Laptop999.9915
Phone699.9942
Tablet449.9928
+

Links

+ View Laptop + View Phone + View Tablet + +""" + + +def extract_links(html): + pattern = r'(.*?)' + for href, text in re.findall(pattern, html): + print(f"{text} -> {href}") + + +def extract_headings(html): + pattern = r"(.*?)" + for heading in re.findall(pattern, html): + print(heading) + + +def extract_table(html): + rows = re.findall(r"(.*?)", html, re.DOTALL) + for row in rows: + cells = re.findall(r"(.*?)", row) + print(",".join(cells)) + + +def extract_text(html): + clean = re.sub(r"<[^>]+>", " ", html) + clean = re.sub(r"\s+", " ", clean).strip() + print(clean) + + +def main(): + target = "links" + for arg in sys.argv[1:]: + if arg.startswith("target="): + target = arg.split("=", 1)[1] + + extractors = { + "links": extract_links, + "headings": extract_headings, + "table": extract_table, + "text": extract_text, + } + + if target not in extractors: + print(f"Error: unknown target '{target}'") + print(f"Available: {', '.join(extractors)}") + sys.exit(1) + + extractors[target](SAMPLE_HTML) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillsbench/skills/json-transform/SKILL.md b/benchmarks/skillsbench/skills/json-transform/SKILL.md new file mode 100644 index 0000000000..318439ba04 --- /dev/null +++ b/benchmarks/skillsbench/skills/json-transform/SKILL.md @@ -0,0 +1,34 @@ +--- +name: json-transform +description: Transform JSON data by flattening nested structures and renaming fields. +--- + +# JSON Transform Skill + +Transform JSON objects by flattening nested structures, renaming keys, and filtering fields. + +## Available Scripts + +### `transform.py` + +Transforms a JSON object according to a field mapping specification. + +**Usage**: `run_skill_script(skill_name="json-transform", script_path="scripts/transform.py", args={"flatten": "true"})` + +The script reads the embedded sample data and applies transformations: +- `flatten=true`: Flatten nested objects using dot notation +- `rename=old:new`: Rename a field (can be specified multiple times) +- `keep=field1,field2`: Keep only specified fields + +**Output format**: Pretty-printed JSON + +## References + +- [sample-data.md](./references/sample-data.md) — Sample nested JSON for testing + +## Workflow + +1. Use `load_skill` to read these instructions. +2. Use `load_skill_resource` to examine the sample data. +3. Use `run_skill_script` to transform the data. +4. Present the transformed JSON to the user. diff --git a/benchmarks/skillsbench/skills/json-transform/references/sample-data.md b/benchmarks/skillsbench/skills/json-transform/references/sample-data.md new file mode 100644 index 0000000000..24b99bb140 --- /dev/null +++ b/benchmarks/skillsbench/skills/json-transform/references/sample-data.md @@ -0,0 +1,21 @@ +# Sample JSON Data + +Use this nested JSON as input for the transform script: + +```json +{ + "user": { + "name": "Alice", + "age": 30, + "address": { + "city": "Seattle", + "state": "WA", + "zip": "98101" + } + }, + "orders": [ + {"id": 1, "total": 42.50}, + {"id": 2, "total": 18.75} + ] +} +``` diff --git a/benchmarks/skillsbench/skills/json-transform/scripts/transform.py b/benchmarks/skillsbench/skills/json-transform/scripts/transform.py new file mode 100644 index 0000000000..323f06ea49 --- /dev/null +++ b/benchmarks/skillsbench/skills/json-transform/scripts/transform.py @@ -0,0 +1,63 @@ +"""Transform JSON by flattening nested structures.""" + +import json +import sys + +SAMPLE_DATA = { + "user": { + "name": "Alice", + "age": 30, + "address": { + "city": "Seattle", + "state": "WA", + "zip": "98101", + }, + }, + "orders": [ + {"id": 1, "total": 42.50}, + {"id": 2, "total": 18.75}, + ], +} + + +def flatten(obj, prefix=""): + result = {} + for key, value in obj.items(): + full_key = f"{prefix}.{key}" if prefix else key + if isinstance(value, dict): + result.update(flatten(value, full_key)) + else: + result[full_key] = value + return result + + +def parse_args(args): + params = {} + for arg in args: + if "=" in arg: + key, value = arg.split("=", 1) + params[key] = value + return params + + +def main(): + params = parse_args(sys.argv[1:]) + data = SAMPLE_DATA.copy() + + if params.get("flatten", "").lower() == "true": + data = flatten(data) + + if "keep" in params: + keep_fields = set(params["keep"].split(",")) + data = {k: v for k, v in data.items() if k in keep_fields} + + if "rename" in params: + old_name, new_name = params["rename"].split(":", 1) + if old_name in data: + data[new_name] = data.pop(old_name) + + print(json.dumps(data, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillsbench/skills/log-parsing/SKILL.md b/benchmarks/skillsbench/skills/log-parsing/SKILL.md new file mode 100644 index 0000000000..de490cb092 --- /dev/null +++ b/benchmarks/skillsbench/skills/log-parsing/SKILL.md @@ -0,0 +1,48 @@ +--- +name: log-parsing +description: Parse and analyze structured log files to extract error patterns and statistics. +metadata: + category: system-admin + aliases: log-analyzer,syslog-parser +--- + +# Log Parsing Skill + +Parse structured log files to extract error counts, warning summaries, and time-based patterns. Supports common log formats. + +## Available Scripts + +### `parse.py` + +Analyzes embedded sample log data and produces a summary report. + +**Usage**: `run_skill_script(skill_name="log-parsing", script_path="scripts/parse.py", args={"level": "ERROR"})` + +Arguments: +- `level`: Filter by log level (DEBUG, INFO, WARNING, ERROR, ALL). Default: ALL +- `format`: Output format (summary, detail, timeline). Default: summary + +**Output format** (summary): +``` +Log Analysis Report +=================== +Total entries: +ERROR: +WARNING: +INFO: +DEBUG: +``` + +**Output format** (detail): +Lists each matching log entry with timestamp and message. + +## References + +- [sample-logs.md](./references/sample-logs.md) — Sample log data for testing + +## Workflow + +1. Use `load_skill` to read these instructions. +2. Optionally use `load_skill_resource` to examine the sample log data. +3. Use `run_skill_script` with the desired log level filter. +4. Present the analysis report to the user. diff --git a/benchmarks/skillsbench/skills/log-parsing/references/sample-logs.md b/benchmarks/skillsbench/skills/log-parsing/references/sample-logs.md new file mode 100644 index 0000000000..90163597a0 --- /dev/null +++ b/benchmarks/skillsbench/skills/log-parsing/references/sample-logs.md @@ -0,0 +1,18 @@ +# Sample Log Data + +The parsing script processes these embedded log entries: + +``` +2024-01-15 10:00:01 INFO Server started on port 8080 +2024-01-15 10:00:05 DEBUG Database connection pool initialized +2024-01-15 10:01:12 INFO User alice logged in +2024-01-15 10:02:33 WARNING High memory usage: 85% +2024-01-15 10:03:45 ERROR Failed to process request: timeout +2024-01-15 10:04:01 INFO User bob logged in +2024-01-15 10:05:22 ERROR Database query failed: connection reset +2024-01-15 10:06:10 WARNING Disk space low: 10% remaining +2024-01-15 10:07:00 INFO Scheduled backup started +2024-01-15 10:08:15 ERROR Backup failed: permission denied +2024-01-15 10:09:30 INFO User alice logged out +2024-01-15 10:10:00 DEBUG Cache cleared +``` diff --git a/benchmarks/skillsbench/skills/log-parsing/scripts/parse.py b/benchmarks/skillsbench/skills/log-parsing/scripts/parse.py new file mode 100644 index 0000000000..f7c658fedb --- /dev/null +++ b/benchmarks/skillsbench/skills/log-parsing/scripts/parse.py @@ -0,0 +1,79 @@ +"""Parse and analyze structured log files.""" + +import sys + +SAMPLE_LOGS = """2024-01-15 10:00:01 INFO Server started on port 8080 +2024-01-15 10:00:05 DEBUG Database connection pool initialized +2024-01-15 10:01:12 INFO User alice logged in +2024-01-15 10:02:33 WARNING High memory usage: 85% +2024-01-15 10:03:45 ERROR Failed to process request: timeout +2024-01-15 10:04:01 INFO User bob logged in +2024-01-15 10:05:22 ERROR Database query failed: connection reset +2024-01-15 10:06:10 WARNING Disk space low: 10% remaining +2024-01-15 10:07:00 INFO Scheduled backup started +2024-01-15 10:08:15 ERROR Backup failed: permission denied +2024-01-15 10:09:30 INFO User alice logged out +2024-01-15 10:10:00 DEBUG Cache cleared""" + + +def parse_entry(line): + parts = line.split(None, 3) + if len(parts) < 4: + return None + date, time, level, message = parts + return { + "timestamp": f"{date} {time}", + "level": level.strip(), + "message": message.strip(), + } + + +def parse_args(args): + params = {} + for arg in args: + if "=" in arg: + key, value = arg.split("=", 1) + params[key] = value + return params + + +def main(): + params = parse_args(sys.argv[1:]) + level_filter = params.get("level", "ALL").upper() + out_format = params.get("format", "summary") + + entries = [] + for line in SAMPLE_LOGS.strip().split("\n"): + entry = parse_entry(line) + if entry: + entries.append(entry) + + if level_filter != "ALL": + filtered = [e for e in entries if e["level"] == level_filter] + else: + filtered = entries + + if out_format == "summary": + counts = {} + for entry in entries: + level = entry["level"] + counts[level] = counts.get(level, 0) + 1 + + print("Log Analysis Report") + print("===================") + print(f"Total entries: {len(entries)}") + for level in ["ERROR", "WARNING", "INFO", "DEBUG"]: + print(f"{level}: {counts.get(level, 0)}") + + elif out_format == "detail": + for entry in filtered: + print(f"[{entry['timestamp']}] {entry['level']} - {entry['message']}") + + elif out_format == "timeline": + for entry in filtered: + time_part = entry["timestamp"].split(" ")[1] + print(f"{time_part} {entry['level']}: {entry['message']}") + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillsbench/skills/regex-replace/SKILL.md b/benchmarks/skillsbench/skills/regex-replace/SKILL.md new file mode 100644 index 0000000000..dde28fc8ca --- /dev/null +++ b/benchmarks/skillsbench/skills/regex-replace/SKILL.md @@ -0,0 +1,36 @@ +--- +name: regex-replace +description: Perform regex-based find-and-replace operations on text input. +--- + +# Regex Replace Skill + +Apply regular expression patterns to find and replace text. Supports basic and advanced regex syntax. + +## Available Scripts + +### `replace.py` + +Performs regex find-and-replace on input text. + +**Usage**: `run_skill_script(skill_name="regex-replace", script_path="scripts/replace.py", args={"pattern": "\\d+", "replacement": "NUM", "text": "Order 123 has 45 items at $67"})` + +Arguments: +- `pattern`: The regex pattern to match +- `replacement`: The replacement string +- `text`: The input text to process +- `count`: Maximum replacements (default: all) + +**Output format**: +``` +Original: +Pattern: +Result: +Matches: +``` + +## Workflow + +1. Use `load_skill` to read these instructions. +2. Use `run_skill_script` with pattern, replacement, and text arguments. +3. Present the transformation result to the user. diff --git a/benchmarks/skillsbench/skills/regex-replace/scripts/replace.py b/benchmarks/skillsbench/skills/regex-replace/scripts/replace.py new file mode 100644 index 0000000000..4e4182bb7c --- /dev/null +++ b/benchmarks/skillsbench/skills/regex-replace/scripts/replace.py @@ -0,0 +1,54 @@ +"""Perform regex find-and-replace on text.""" + +import re +import sys + + +def parse_args(args): + params = {} + current_key = None + current_val = [] + for arg in args: + if "=" in arg and not current_key: + key, value = arg.split("=", 1) + if value.startswith("'") and not value.endswith("'"): + current_key = key + current_val = [value[1:]] + elif value.startswith("'") and value.endswith("'"): + params[key] = value[1:-1] + else: + params[key] = value + elif current_key: + if arg.endswith("'"): + current_val.append(arg[:-1]) + params[current_key] = " ".join(current_val) + current_key = None + current_val = [] + else: + current_val.append(arg) + if current_key: + params[current_key] = " ".join(current_val) + return params + + +def main(): + params = parse_args(sys.argv[1:]) + pattern = params.get("pattern", r"\d+") + replacement = params.get("replacement", "NUM") + text = params.get("text", "Order 123 has 45 items at $67") + count = int(params.get("count", "0")) + + matches = re.findall(pattern, text) + if count > 0: + result = re.sub(pattern, replacement, text, count=count) + else: + result = re.sub(pattern, replacement, text) + + print(f"Original: {text}") + print(f"Pattern: {pattern}") + print(f"Result: {result}") + print(f"Matches: {len(matches)}") + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillsbench/skills/rest-client/SKILL.md b/benchmarks/skillsbench/skills/rest-client/SKILL.md new file mode 100644 index 0000000000..8033ee4c68 --- /dev/null +++ b/benchmarks/skillsbench/skills/rest-client/SKILL.md @@ -0,0 +1,40 @@ +--- +name: rest-client +description: Simulate REST API interactions by constructing and executing HTTP-like requests. +--- + +# REST Client Skill + +Build and execute simulated REST API requests against an embedded mock API. Demonstrates multi-step skill usage with request construction and response parsing. + +## Available Scripts + +### `request.py` + +Executes a simulated REST API request against a mock endpoint. + +**Usage**: `run_skill_script(skill_name="rest-client", script_path="scripts/request.py", args={"method": "GET", "endpoint": "/users"})` + +Supported arguments: +- `method`: HTTP method (GET, POST, PUT, DELETE) +- `endpoint`: API path (e.g., `/users`, `/users/1`, `/products`) +- `body`: JSON body for POST/PUT requests + +Available mock endpoints: +- `GET /users` — List all users +- `GET /users/` — Get user by ID +- `POST /users` — Create a user (requires `body`) +- `GET /products` — List all products + +**Output format**: JSON response with status code + +## References + +- [api-docs.md](./references/api-docs.md) — Mock API documentation + +## Workflow + +1. Use `load_skill` to read these instructions. +2. Use `load_skill_resource` to review the API documentation. +3. Use `run_skill_script` to make API requests. +4. Parse the response and present the data to the user. diff --git a/benchmarks/skillsbench/skills/rest-client/references/api-docs.md b/benchmarks/skillsbench/skills/rest-client/references/api-docs.md new file mode 100644 index 0000000000..75bf900276 --- /dev/null +++ b/benchmarks/skillsbench/skills/rest-client/references/api-docs.md @@ -0,0 +1,36 @@ +# Mock API Documentation + +## Base URL + +All endpoints are relative to the mock server. + +## Endpoints + +### GET /users +Returns a list of all users. + +**Response**: +```json +[ + {"id": 1, "name": "Alice", "email": "alice@example.com"}, + {"id": 2, "name": "Bob", "email": "bob@example.com"}, + {"id": 3, "name": "Carol", "email": "carol@example.com"} +] +``` + +### GET /users/:id +Returns a single user by ID. + +### POST /users +Creates a new user. Requires a JSON body with `name` and `email` fields. + +### GET /products +Returns a list of all products. + +**Response**: +```json +[ + {"id": 1, "name": "Laptop", "price": 999.99}, + {"id": 2, "name": "Phone", "price": 699.99} +] +``` diff --git a/benchmarks/skillsbench/skills/rest-client/scripts/request.py b/benchmarks/skillsbench/skills/rest-client/scripts/request.py new file mode 100644 index 0000000000..dd22bc9c84 --- /dev/null +++ b/benchmarks/skillsbench/skills/rest-client/scripts/request.py @@ -0,0 +1,65 @@ +"""Simulate REST API requests against a mock server.""" + +import json +import sys + +MOCK_DB = { + "users": [ + {"id": 1, "name": "Alice", "email": "alice@example.com"}, + {"id": 2, "name": "Bob", "email": "bob@example.com"}, + {"id": 3, "name": "Carol", "email": "carol@example.com"}, + ], + "products": [ + {"id": 1, "name": "Laptop", "price": 999.99}, + {"id": 2, "name": "Phone", "price": 699.99}, + ], +} + + +def parse_args(args): + params = {} + for arg in args: + if "=" in arg: + key, value = arg.split("=", 1) + params[key] = value + return params + + +def handle_request(method, endpoint, body=None): + method = method.upper() + + if endpoint == "/users" and method == "GET": + return 200, MOCK_DB["users"] + + if endpoint.startswith("/users/") and method == "GET": + user_id = int(endpoint.split("/")[-1]) + for user in MOCK_DB["users"]: + if user["id"] == user_id: + return 200, user + return 404, {"error": "User not found"} + + if endpoint == "/users" and method == "POST": + if body: + new_user = json.loads(body) + new_user["id"] = len(MOCK_DB["users"]) + 1 + return 201, new_user + return 400, {"error": "Request body required"} + + if endpoint == "/products" and method == "GET": + return 200, MOCK_DB["products"] + + return 404, {"error": f"Unknown endpoint: {method} {endpoint}"} + + +def main(): + params = parse_args(sys.argv[1:]) + method = params.get("method", "GET") + endpoint = params.get("endpoint", "/users") + body = params.get("body") + + status, response = handle_request(method, endpoint, body) + print(json.dumps({"status": status, "data": response}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/skillsbench/skills/statistical-calc/SKILL.md b/benchmarks/skillsbench/skills/statistical-calc/SKILL.md new file mode 100644 index 0000000000..0c8044dcb0 --- /dev/null +++ b/benchmarks/skillsbench/skills/statistical-calc/SKILL.md @@ -0,0 +1,38 @@ +--- +name: statistical-calc +description: Compute descriptive statistics (mean, median, std dev, percentiles) for numeric datasets. +--- + +# Statistical Calc Skill + +Compute descriptive statistics on numeric data including mean, median, standard deviation, variance, and percentiles. + +## Available Scripts + +### `stats.py` + +Computes descriptive statistics for a list of numbers. + +**Usage**: `run_skill_script(skill_name="statistical-calc", script_path="scripts/stats.py", args={"data": "10,20,30,40,50,60,70,80,90,100"})` + +Arguments: +- `data`: Comma-separated list of numbers + +**Output format**: +``` +Count: +Mean: +Median: +Std Dev: +Variance: +Min: +Max: +P25: <25th percentile> +P75: <75th percentile> +``` + +## Workflow + +1. Use `load_skill` to read these instructions. +2. Use `run_skill_script` with numeric data to compute statistics. +3. Present the statistics to the user. diff --git a/benchmarks/skillsbench/skills/statistical-calc/scripts/stats.py b/benchmarks/skillsbench/skills/statistical-calc/scripts/stats.py new file mode 100644 index 0000000000..f6d893dc92 --- /dev/null +++ b/benchmarks/skillsbench/skills/statistical-calc/scripts/stats.py @@ -0,0 +1,54 @@ +"""Compute descriptive statistics for numeric data.""" + +import math +import sys + + +def parse_args(args): + params = {} + for arg in args: + if "=" in arg: + key, value = arg.split("=", 1) + params[key] = value + return params + + +def percentile(sorted_data, p): + k = (len(sorted_data) - 1) * (p / 100.0) + f = math.floor(k) + c = math.ceil(k) + if f == c: + return sorted_data[int(k)] + return sorted_data[int(f)] * (c - k) + sorted_data[int(c)] * (k - f) + + +def main(): + params = parse_args(sys.argv[1:]) + data_str = params.get("data", "10,20,30,40,50,60,70,80,90,100") + data = [float(x.strip()) for x in data_str.split(",")] + + n = len(data) + mean = sum(data) / n + sorted_data = sorted(data) + + if n % 2 == 0: + median = (sorted_data[n // 2 - 1] + sorted_data[n // 2]) / 2 + else: + median = sorted_data[n // 2] + + variance = sum((x - mean) ** 2 for x in data) / n + std_dev = math.sqrt(variance) + + print(f"Count: {n}") + print(f"Mean: {mean:.2f}") + print(f"Median: {median:.2f}") + print(f"Std Dev: {std_dev:.2f}") + print(f"Variance: {variance:.2f}") + print(f"Min: {min(data):.2f}") + print(f"Max: {max(data):.2f}") + print(f"P25: {percentile(sorted_data, 25):.2f}") + print(f"P75: {percentile(sorted_data, 75):.2f}") + + +if __name__ == "__main__": + main() diff --git a/contributing/samples/gepa/experiment.py b/contributing/samples/gepa/experiment.py index f3751206a8..2710c3894c 100644 --- a/contributing/samples/gepa/experiment.py +++ b/contributing/samples/gepa/experiment.py @@ -43,7 +43,6 @@ from tau_bench.types import EnvRunResult from tau_bench.types import RunConfig import tau_bench_agent as tau_bench_agent_lib - import utils diff --git a/contributing/samples/gepa/run_experiment.py b/contributing/samples/gepa/run_experiment.py index d857da9635..e31db15788 100644 --- a/contributing/samples/gepa/run_experiment.py +++ b/contributing/samples/gepa/run_experiment.py @@ -25,7 +25,6 @@ from absl import flags import experiment from google.genai import types - import utils _OUTPUT_DIR = flags.DEFINE_string( diff --git a/contributing/samples/human_in_loop/main.py b/contributing/samples/human_in_loop/main.py index c7ad041b23..3103da9147 100644 --- a/contributing/samples/human_in_loop/main.py +++ b/contributing/samples/human_in_loop/main.py @@ -113,8 +113,8 @@ async def call_agent(query: str): updated_tool_output_data = { "status": "approved", "ticketId": ticket_id, - "approver_feedback": ( - "Approved by manager at " + str(asyncio.get_event_loop().time()) + "approver_feedback": "Approved by manager at " + str( + asyncio.get_event_loop().time() ), } diff --git a/contributing/samples/skill_script_demo/__init__.py b/contributing/samples/skill_script_demo/__init__.py new file mode 100644 index 0000000000..4015e47d6e --- /dev/null +++ b/contributing/samples/skill_script_demo/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from . import agent diff --git a/contributing/samples/skill_script_demo/agent.py b/contributing/samples/skill_script_demo/agent.py new file mode 100644 index 0000000000..3c400224d5 --- /dev/null +++ b/contributing/samples/skill_script_demo/agent.py @@ -0,0 +1,53 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Sample agent with multiple skills and script execution. + +This agent loads the Anthropic mcp-builder skill and a python-helper +skill, exercising all skill tools: list_skills, load_skill, +load_skill_resource, and execute_skill_script. + +WARNING: This sample uses UnsafeLocalCodeExecutor, which runs scripts +in the host process with no sandboxing. For production use, prefer +ContainerCodeExecutor or VertexAICodeExecutor for isolation. +""" + +import pathlib + +from google.adk import Agent +from google.adk.code_executors.unsafe_local_code_executor import UnsafeLocalCodeExecutor +from google.adk.skills import load_skill_from_dir +from google.adk.tools.skill_toolset import SkillToolset + +_SKILLS_DIR = pathlib.Path(__file__).parent / "skills" + +mcp_builder_skill = load_skill_from_dir(_SKILLS_DIR / "mcp-builder") +python_helper_skill = load_skill_from_dir(_SKILLS_DIR / "python-helper") + +# WARNING: UnsafeLocalCodeExecutor runs code in the host process. +# For production, use ContainerCodeExecutor or VertexAICodeExecutor. +my_skill_toolset = SkillToolset( + skills=[mcp_builder_skill, python_helper_skill], + code_executor=UnsafeLocalCodeExecutor(), +) + +root_agent = Agent( + model="gemini-2.5-flash", + name="skill_script_demo_agent", + description=( + "An agent that demonstrates skill script execution using" + " the mcp-builder and python-helper skills." + ), + tools=[my_skill_toolset], +) diff --git a/contributing/samples/skill_script_demo/run_live_test.py b/contributing/samples/skill_script_demo/run_live_test.py new file mode 100644 index 0000000000..2315e1c4da --- /dev/null +++ b/contributing/samples/skill_script_demo/run_live_test.py @@ -0,0 +1,759 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Live integration test: realistic skill workflows with Gemini. + +Exercises the full skill lifecycle — discovery, loading, reference +reading, script inspection, and script execution — using both +Anthropic's mcp-builder skill and a lightweight python-helper skill. + +Usage: + export GOOGLE_CLOUD_PROJECT=your-project-id + python contributing/samples/skill_script_demo/run_live_test.py +""" + +import asyncio +import os +import pathlib +import subprocess +import sys +import traceback + +# Ensure the repo src is on the path +sys.path.insert(0, str(pathlib.Path(__file__).parents[3] / "src")) + +from google.adk import Agent +from google.adk.code_executors.unsafe_local_code_executor import UnsafeLocalCodeExecutor +from google.adk.runners import Runner +from google.adk.sessions import InMemorySessionService +from google.adk.skills import load_skill_from_dir +from google.adk.tools.skill_toolset import SkillToolset +from google.genai import types + +_SKILLS_DIR = pathlib.Path(__file__).parent / "skills" + +# Configure for Vertex AI +project = os.environ.get("GOOGLE_CLOUD_PROJECT") +if not project: + try: + result = subprocess.run( + ["gcloud", "config", "get-value", "project"], + capture_output=True, + text=True, + timeout=10, + ) + project = result.stdout.strip() + except (FileNotFoundError, subprocess.TimeoutExpired): + project = "" + if project: + os.environ["GOOGLE_CLOUD_PROJECT"] = project + +os.environ.setdefault("GOOGLE_GENAI_USE_VERTEXAI", "TRUE") +os.environ.setdefault("GOOGLE_CLOUD_LOCATION", "us-central1") + + +def build_agent(): + """Build the agent with mcp-builder and python-helper skills.""" + mcp_builder = load_skill_from_dir(_SKILLS_DIR / "mcp-builder") + python_helper = load_skill_from_dir(_SKILLS_DIR / "python-helper") + + toolset = SkillToolset( + skills=[mcp_builder, python_helper], + code_executor=UnsafeLocalCodeExecutor(), + ) + + return Agent( + model="gemini-2.5-flash", + name="skill_test_agent", + description=( + "An agent that uses skills for MCP development and Python utilities." + ), + tools=[toolset], + ) + + +# ── Event extraction helpers ──────────────────────────────────── + + +def extract_tool_calls(events): + """Extract tool call names from events.""" + names = [] + for ev in events: + if not ev.content or not ev.content.parts: + continue + for part in ev.content.parts: + if part.function_call: + names.append(part.function_call.name) + return names + + +def extract_tool_call_args(events): + """Extract tool calls with their arguments.""" + calls = [] + for ev in events: + if not ev.content or not ev.content.parts: + continue + for part in ev.content.parts: + if part.function_call: + calls.append({ + "name": part.function_call.name, + "args": dict(part.function_call.args or {}), + }) + return calls + + +def extract_tool_responses(events): + """Extract function response payloads.""" + responses = [] + for ev in events: + if not ev.content or not ev.content.parts: + continue + for part in ev.content.parts: + if part.function_response: + responses.append({ + "name": part.function_response.name, + "response": part.function_response.response, + }) + return responses + + +def extract_final_text(events): + """Extract the final text response.""" + for ev in reversed(events): + if not ev.content or not ev.content.parts: + continue + for part in ev.content.parts: + if part.text: + return part.text + return "" + + +# ── Query runner ──────────────────────────────────────────────── + + +async def run_query(runner, session_id, user_id, query): + """Send a query and collect all events.""" + content = types.Content( + role="user", + parts=[types.Part.from_text(text=query)], + ) + events = [] + async for event in runner.run_async( + user_id=user_id, + session_id=session_id, + new_message=content, + ): + events.append(event) + return events + + +# ── Check engine ──────────────────────────────────────────────── + +SKILL_TOOLS = frozenset([ + "list_skills", + "load_skill", + "load_skill_resource", + "execute_skill_script", +]) + + +def check(tc, tool_calls, call_args, responses, text): + """Run all checks for a test step. Returns (ok, messages).""" + ok = True + msgs = [] + + # ── expect_tools: every listed tool must appear ── + for t in tc.get("expect_tools", []): + if t in tool_calls: + msgs.append(f" PASS: Used '{t}'") + else: + msgs.append(f" FAIL: Expected '{t}' in {tool_calls}") + ok = False + + # ── expect_any_tool: at least one must appear ── + any_tools = tc.get("expect_any_tool", []) + if any_tools: + matched = [t for t in any_tools if t in tool_calls] + if matched: + msgs.append(f" PASS: Used one of {any_tools}: {matched}") + else: + msgs.append(f" FAIL: Expected one of {any_tools} in {tool_calls}") + ok = False + + # ── expect_no_skill_tools ── + if tc.get("expect_no_skill_tools"): + used = [t for t in tool_calls if t in SKILL_TOOLS] + if used: + msgs.append(f" FAIL: Should NOT have used: {used}") + ok = False + else: + msgs.append(" PASS: No skill tools used") + + # ── expect_text_contains ── + for s in tc.get("expect_text_contains", []): + if s.lower() in text.lower(): + msgs.append(f" PASS: Response contains '{s}'") + else: + msgs.append(f" FAIL: Response missing '{s}'") + ok = False + + # ── expect_text_any ── + text_any = tc.get("expect_text_any", []) + if text_any: + found = [s for s in text_any if s.lower() in text.lower()] + if found: + msgs.append(f" PASS: Response contains one of: {found}") + else: + msgs.append(f" FAIL: Response missing all of: {text_any}") + ok = False + + # ── expect_execute_script: verify execute call args ── + ex = tc.get("expect_execute_script") + if ex: + exec_calls = [c for c in call_args if c["name"] == "execute_skill_script"] + if not exec_calls: + msgs.append(f" FAIL: No execute_skill_script call in {tool_calls}") + ok = False + else: + c = exec_calls[0] + if "skill_name" in ex: + actual = c["args"].get("skill_name") + if actual == ex["skill_name"]: + msgs.append(f" PASS: skill_name='{actual}'") + else: + msgs.append( + " FAIL: skill_name: expected" + f" '{ex['skill_name']}' got '{actual}'" + ) + ok = False + if "script_name" in ex: + actual = c["args"].get("script_name", "") + expected = ex["script_name"] + if actual == expected or actual == f"scripts/{expected}": + msgs.append(f" PASS: script_name='{actual}'") + else: + msgs.append( + f" FAIL: script_name: expected '{expected}' got '{actual}'" + ) + ok = False + if "has_input_args" in ex: + has = bool(c["args"].get("input_args")) + if has == ex["has_input_args"]: + msgs.append(f" PASS: input_args present={has}") + else: + msgs.append( + " FAIL: input_args: expected" + f" present={ex['has_input_args']} got {has}" + ) + ok = False + + # ── expect_script_output: verify execution result ── + out = tc.get("expect_script_output") + if out: + exec_resps = [r for r in responses if r["name"] == "execute_skill_script"] + if not exec_resps: + msgs.append(" FAIL: No execute_skill_script response") + ok = False + else: + resp = exec_resps[0]["response"] + expect_status = out.get("status", "success") + actual_status = resp.get("status", "") + if actual_status == expect_status: + msgs.append(f" PASS: Script status='{actual_status}'") + else: + msgs.append( + " FAIL: Script status: expected" + f" '{expect_status}' got '{actual_status}'" + f" error={resp.get('error', '')}" + ) + ok = False + + stdout = resp.get("stdout", "") + for s in out.get("stdout_contains", []): + if s.lower() in stdout.lower(): + msgs.append(f" PASS: stdout contains '{s}'") + else: + msgs.append(f" FAIL: stdout missing '{s}'") + ok = False + + stderr = resp.get("stderr", "") + for s in out.get("stderr_contains", []): + if s.lower() in stderr.lower(): + msgs.append(f" PASS: stderr contains '{s}'") + else: + msgs.append(f" FAIL: stderr missing '{s}'") + ok = False + + # ── expect_resource_loaded: verify load_skill_resource resp ── + res = tc.get("expect_resource_loaded") + if res: + res_resps = [r for r in responses if r["name"] == "load_skill_resource"] + if not res_resps: + msgs.append(" FAIL: No load_skill_resource response") + ok = False + else: + for r in res_resps: + content = r["response"].get("content", "") + for s in res.get("content_contains", []): + if s.lower() in content.lower(): + msgs.append(f" PASS: Resource contains '{s}'") + else: + msgs.append(f" FAIL: Resource missing '{s}'") + ok = False + + return ok, msgs + + +# ── Test scenarios ────────────────────────────────────────────── + + +def get_test_scenarios(): + """Return test scenario groups.""" + return [ + # ───────────────────────────────────────────────────────── + # Scenario 1: Discover both skills + # ───────────────────────────────────────────────────────── + { + "name": "Scenario 1: Discover both skills", + "shared_session": False, + "steps": [{ + "name": "1a: List all available skills", + "query": ( + "What skills do you have? List them all" + " with their descriptions." + ), + "expect_any_tool": ["list_skills", "load_skill"], + "expect_text_contains": [ + "mcp-builder", + "python-helper", + ], + }], + }, + # ───────────────────────────────────────────────────────── + # Scenario 2: MCP development — load skill & read reference + # ───────────────────────────────────────────────────────── + { + "name": ( + "Scenario 2: MCP dev workflow — load skill, read Python reference" + ), + "shared_session": True, + "steps": [ + { + "name": ( + "2a: Load mcp-builder and ask about" + " Python server patterns" + ), + "query": ( + "I want to build an MCP server in" + " Python using FastMCP. Load the" + " mcp-builder skill and tell me the" + " four workflow phases." + ), + "expect_tools": ["load_skill"], + "expect_text_any": [ + "Phase", + "Research", + "Implementation", + "Review", + "Evaluation", + ], + }, + { + "name": "2b: Read the Python MCP server reference", + "query": ( + "Now use load_skill_resource to read" + " references/python_mcp_server.md" + " from the mcp-builder skill." + " Summarize the key patterns it" + " recommends for implementing tools." + ), + "expect_tools": ["load_skill_resource"], + "expect_resource_loaded": { + "content_contains": [ + "FastMCP", + "@mcp.tool", + ], + }, + }, + ], + }, + # ───────────────────────────────────────────────────────── + # Scenario 3: Inspect then execute connections.py + # ───────────────────────────────────────────────────────── + { + "name": "Scenario 3: Inspect and execute mcp-builder connections.py", + "shared_session": True, + "steps": [ + { + "name": "3a: Inspect connections.py source", + "query": ( + "Use load_skill_resource to show me" + " the source code of" + " scripts/connections.py from the" + " mcp-builder skill." + ), + "expect_tools": ["load_skill_resource"], + "expect_resource_loaded": { + "content_contains": [ + "MCPConnection", + "create_connection", + ], + }, + }, + { + "name": "3b: Execute connections.py", + "query": ( + "Please execute connections.py from" + " the mcp-builder skill using the" + " execute_skill_script tool. I want" + " to confirm the script loads without" + " errors." + ), + "expect_tools": ["execute_skill_script"], + "expect_execute_script": { + "skill_name": "mcp-builder", + "script_name": "connections.py", + }, + "expect_script_output": { + "status": "success", + }, + }, + ], + }, + # ───────────────────────────────────────────────────────── + # Scenario 4: Read evaluation reference + example XML + # ───────────────────────────────────────────────────────── + { + "name": "Scenario 4: Evaluation workflow — read eval guide & example", + "shared_session": True, + "steps": [ + { + "name": "4a: Read the evaluation guide reference", + "query": ( + "Use load_skill_resource to read" + " references/evaluation.md from the" + " mcp-builder skill. Summarize the" + " key requirements for a good" + " evaluation question." + ), + "expect_tools": ["load_skill_resource"], + "expect_resource_loaded": { + "content_contains": ["qa_pair"], + }, + "expect_text_any": [ + "independent", + "read-only", + "verifiable", + "stable", + "non-destructive", + ], + }, + { + "name": "4b: Read the example evaluation XML", + "query": ( + "Now use load_skill_resource to read" + " scripts/example_evaluation.xml from" + " the mcp-builder skill and tell me" + " how many QA pairs it contains and" + " what topics they cover." + ), + "expect_tools": ["load_skill_resource"], + "expect_resource_loaded": { + "content_contains": [ + "qa_pair", + "compound interest", + ], + }, + "expect_text_any": ["5", "five"], + }, + ], + }, + # ───────────────────────────────────────────────────────── + # Scenario 5: Execute fibonacci with python-helper + # ───────────────────────────────────────────────────────── + { + "name": "Scenario 5: Execute python-helper fibonacci script", + "shared_session": False, + "steps": [{ + "name": "5a: Generate first 8 Fibonacci numbers", + "query": ( + "Use the python-helper skill to run" + " fibonacci.py and generate the first 8" + " Fibonacci numbers." + ), + "expect_tools": ["execute_skill_script"], + "expect_execute_script": { + "skill_name": "python-helper", + "script_name": "fibonacci.py", + "has_input_args": True, + }, + "expect_script_output": { + "status": "success", + "stdout_contains": ["Fibonacci"], + }, + "expect_text_any": ["13", "0, 1, 1, 2, 3, 5, 8, 13"], + }], + }, + # ───────────────────────────────────────────────────────── + # Scenario 6: Execute word_count with python-helper + # ───────────────────────────────────────────────────────── + { + "name": "Scenario 6: Execute python-helper word_count script", + "shared_session": False, + "steps": [{ + "name": "6a: Analyze word frequency", + "query": ( + "Use the python-helper skill to run" + " word_count.py on the text: 'to be or" + " not to be that is the question'" + ), + "expect_tools": ["execute_skill_script"], + "expect_execute_script": { + "skill_name": "python-helper", + "script_name": "word_count.py", + "has_input_args": True, + }, + "expect_script_output": { + "status": "success", + "stdout_contains": [ + "Total words", + "Unique words", + ], + }, + "expect_text_any": ["to", "be"], + }], + }, + # ───────────────────────────────────────────────────────── + # Scenario 7: Full multi-turn with MCP builder + execution + # ───────────────────────────────────────────────────────── + { + "name": ( + "Scenario 7: Multi-turn — load mcp-builder," + " read reference, inspect script, execute" + ), + "shared_session": True, + "steps": [ + { + "name": "7a: Load mcp-builder skill and read best practices", + "query": ( + "Load the mcp-builder skill. Then" + " use load_skill_resource to read" + " references/mcp_best_practices.md." + " What does it say about tool naming?" + ), + "expect_tools": ["load_skill_resource"], + "expect_any_tool": [ + "load_skill", + "load_skill_resource", + ], + "expect_resource_loaded": { + "content_contains": ["snake_case"], + }, + "expect_text_any": [ + "snake_case", + "prefix", + "naming", + ], + }, + { + "name": "7b: Inspect connections.py source code", + "query": ( + "Use load_skill_resource to read" + " scripts/connections.py from the" + " mcp-builder skill." + ), + "expect_tools": ["load_skill_resource"], + "expect_resource_loaded": { + "content_contains": [ + "MCPConnection", + ], + }, + }, + { + "name": "7c: Execute connections.py we just inspected", + "query": ( + "I know it only defines classes," + " but please call" + " execute_skill_script with" + " skill_name='mcp-builder' and" + " script_name='connections.py'" + " anyway. If the mcp package is" + " missing the imports will raise" + " an ImportError, which is what" + " I want to check." + ), + "expect_tools": ["execute_skill_script"], + "expect_execute_script": { + "skill_name": "mcp-builder", + "script_name": "connections.py", + }, + "expect_script_output": { + "status": "success", + }, + }, + { + "name": "7d: Now use python-helper to process some data", + "query": ( + "Now switch to the python-helper" + " skill and use json_format.py to" + " pretty-print this JSON:" + ' {"tools":["list_tools",' + '"call_tool"],' + '"transport":"stdio"}' + ), + "expect_tools": ["execute_skill_script"], + "expect_execute_script": { + "skill_name": "python-helper", + "script_name": "json_format.py", + "has_input_args": True, + }, + "expect_script_output": { + "status": "success", + "stdout_contains": [ + "tools", + "transport", + ], + }, + }, + ], + }, + # ───────────────────────────────────────────────────────── + # Scenario 8: Agent routes to the right skill + # ───────────────────────────────────────────────────────── + { + "name": ( + "Scenario 8: Agent picks mcp-builder for" + " MCP questions, not python-helper" + ), + "shared_session": False, + "steps": [{ + "name": "8a: MCP question routes to mcp-builder", + "query": ( + "I need to add pagination to my MCP" + " server's list endpoint. Load the" + " relevant skill and show me the" + " recommended pagination pattern." + ), + "expect_tools": ["load_skill"], + "expect_text_any": [ + "offset", + "limit", + "has_more", + "pagination", + "next_offset", + ], + }], + }, + # ───────────────────────────────────────────────────────── + # Scenario 9: Unrelated query does not use skills + # ───────────────────────────────────────────────────────── + { + "name": "Scenario 9: Unrelated query avoids skills", + "shared_session": False, + "steps": [{ + "name": "9a: Simple math question", + "query": "What is 17 * 23?", + "expect_no_skill_tools": True, + "expect_text_contains": ["391"], + }], + }, + ] + + +# ── Main runner ───────────────────────────────────────────────── + + +async def main(): + agent = build_agent() + session_service = InMemorySessionService() + runner = Runner( + agent=agent, + app_name="skill_live_test", + session_service=session_service, + ) + + user_id = "test_user" + scenarios = get_test_scenarios() + total_passed = 0 + total_failed = 0 + failures = [] + + for scenario in scenarios: + print(f"\n{'#'*60}") + print(f" {scenario['name']}") + print(f"{'#'*60}") + + shared_session = None + if scenario["shared_session"]: + shared_session = await session_service.create_session( + app_name="skill_live_test", user_id=user_id + ) + + for step in scenario["steps"]: + print(f"\n {'─'*54}") + print(f" {step['name']}") + print(f" Query: {step['query'][:80]}...") + + session = shared_session or ( + await session_service.create_session( + app_name="skill_live_test", user_id=user_id + ) + ) + + try: + events = await run_query(runner, session.id, user_id, step["query"]) + except Exception as e: + print(f" ERROR: {e}") + traceback.print_exc() + total_failed += 1 + failures.append((step["name"], str(e))) + continue + + tool_calls = extract_tool_calls(events) + call_args = extract_tool_call_args(events) + responses = extract_tool_responses(events) + text = extract_final_text(events) + + print(f" Tool calls: {tool_calls}") + for c in call_args: + if c["name"] == "execute_skill_script": + print(f" Execute args: {c['args']}") + elif c["name"] == "load_skill_resource": + print(f" Resource: {c['args'].get('path', '?')}") + print(f" Response: {text[:250]}...") + + ok, msgs = check(step, tool_calls, call_args, responses, text) + for msg in msgs: + print(msg) + + if ok: + total_passed += 1 + else: + total_failed += 1 + failures.append((step["name"], "assertion failure")) + + total = total_passed + total_failed + print(f"\n{'='*60}") + print(f" RESULTS: {total_passed}/{total} passed") + if failures: + print(f"\n Failures:") + for name, reason in failures: + print(f" - {name}: {reason}") + print(f"{'='*60}") + return total_failed == 0 + + +if __name__ == "__main__": + success = asyncio.run(main()) + sys.exit(0 if success else 1) diff --git a/contributing/samples/skill_script_demo/skills/mcp-builder/LICENSE.txt b/contributing/samples/skill_script_demo/skills/mcp-builder/LICENSE.txt new file mode 100644 index 0000000000..7a4a3ea242 --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/mcp-builder/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/contributing/samples/skill_script_demo/skills/mcp-builder/SKILL.md b/contributing/samples/skill_script_demo/skills/mcp-builder/SKILL.md new file mode 100644 index 0000000000..5151b00adf --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/mcp-builder/SKILL.md @@ -0,0 +1,236 @@ +--- +name: mcp-builder +description: Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK). +license: Complete terms in LICENSE.txt +--- + +# MCP Server Development Guide + +## Overview + +Create MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. The quality of an MCP server is measured by how well it enables LLMs to accomplish real-world tasks. + +--- + +# Process + +## 🚀 High-Level Workflow + +Creating a high-quality MCP server involves four main phases: + +### Phase 1: Deep Research and Planning + +#### 1.1 Understand Modern MCP Design + +**API Coverage vs. Workflow Tools:** +Balance comprehensive API endpoint coverage with specialized workflow tools. Workflow tools can be more convenient for specific tasks, while comprehensive coverage gives agents flexibility to compose operations. Performance varies by client—some clients benefit from code execution that combines basic tools, while others work better with higher-level workflows. When uncertain, prioritize comprehensive API coverage. + +**Tool Naming and Discoverability:** +Clear, descriptive tool names help agents find the right tools quickly. Use consistent prefixes (e.g., `github_create_issue`, `github_list_repos`) and action-oriented naming. + +**Context Management:** +Agents benefit from concise tool descriptions and the ability to filter/paginate results. Design tools that return focused, relevant data. Some clients support code execution which can help agents filter and process data efficiently. + +**Actionable Error Messages:** +Error messages should guide agents toward solutions with specific suggestions and next steps. + +#### 1.2 Study MCP Protocol Documentation + +**Navigate the MCP specification:** + +Start with the sitemap to find relevant pages: `https://modelcontextprotocol.io/sitemap.xml` + +Then fetch specific pages with `.md` suffix for markdown format (e.g., `https://modelcontextprotocol.io/specification/draft.md`). + +Key pages to review: +- Specification overview and architecture +- Transport mechanisms (streamable HTTP, stdio) +- Tool, resource, and prompt definitions + +#### 1.3 Study Framework Documentation + +**Recommended stack:** +- **Language**: TypeScript (high-quality SDK support and good compatibility in many execution environments e.g. MCPB. Plus AI models are good at generating TypeScript code, benefiting from its broad usage, static typing and good linting tools) +- **Transport**: Streamable HTTP for remote servers, using stateless JSON (simpler to scale and maintain, as opposed to stateful sessions and streaming responses). stdio for local servers. + +**Load framework documentation:** + +- **MCP Best Practices**: [📋 View Best Practices](./references/mcp_best_practices.md) - Core guidelines + +**For TypeScript (recommended):** +- **TypeScript SDK**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md` +- [⚡ TypeScript Guide](./references/node_mcp_server.md) - TypeScript patterns and examples + +**For Python:** +- **Python SDK**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md` +- [🐍 Python Guide](./references/python_mcp_server.md) - Python patterns and examples + +#### 1.4 Plan Your Implementation + +**Understand the API:** +Review the service's API documentation to identify key endpoints, authentication requirements, and data models. Use web search and WebFetch as needed. + +**Tool Selection:** +Prioritize comprehensive API coverage. List endpoints to implement, starting with the most common operations. + +--- + +### Phase 2: Implementation + +#### 2.1 Set Up Project Structure + +See language-specific guides for project setup: +- [⚡ TypeScript Guide](./references/node_mcp_server.md) - Project structure, package.json, tsconfig.json +- [🐍 Python Guide](./references/python_mcp_server.md) - Module organization, dependencies + +#### 2.2 Implement Core Infrastructure + +Create shared utilities: +- API client with authentication +- Error handling helpers +- Response formatting (JSON/Markdown) +- Pagination support + +#### 2.3 Implement Tools + +For each tool: + +**Input Schema:** +- Use Zod (TypeScript) or Pydantic (Python) +- Include constraints and clear descriptions +- Add examples in field descriptions + +**Output Schema:** +- Define `outputSchema` where possible for structured data +- Use `structuredContent` in tool responses (TypeScript SDK feature) +- Helps clients understand and process tool outputs + +**Tool Description:** +- Concise summary of functionality +- Parameter descriptions +- Return type schema + +**Implementation:** +- Async/await for I/O operations +- Proper error handling with actionable messages +- Support pagination where applicable +- Return both text content and structured data when using modern SDKs + +**Annotations:** +- `readOnlyHint`: true/false +- `destructiveHint`: true/false +- `idempotentHint`: true/false +- `openWorldHint`: true/false + +--- + +### Phase 3: Review and Test + +#### 3.1 Code Quality + +Review for: +- No duplicated code (DRY principle) +- Consistent error handling +- Full type coverage +- Clear tool descriptions + +#### 3.2 Build and Test + +**TypeScript:** +- Run `npm run build` to verify compilation +- Test with MCP Inspector: `npx @modelcontextprotocol/inspector` + +**Python:** +- Verify syntax: `python -m py_compile your_server.py` +- Test with MCP Inspector + +See language-specific guides for detailed testing approaches and quality checklists. + +--- + +### Phase 4: Create Evaluations + +After implementing your MCP server, create comprehensive evaluations to test its effectiveness. + +**Load [✅ Evaluation Guide](./references/evaluation.md) for complete evaluation guidelines.** + +#### 4.1 Understand Evaluation Purpose + +Use evaluations to test whether LLMs can effectively use your MCP server to answer realistic, complex questions. + +#### 4.2 Create 10 Evaluation Questions + +To create effective evaluations, follow the process outlined in the evaluation guide: + +1. **Tool Inspection**: List available tools and understand their capabilities +2. **Content Exploration**: Use READ-ONLY operations to explore available data +3. **Question Generation**: Create 10 complex, realistic questions +4. **Answer Verification**: Solve each question yourself to verify answers + +#### 4.3 Evaluation Requirements + +Ensure each question is: +- **Independent**: Not dependent on other questions +- **Read-only**: Only non-destructive operations required +- **Complex**: Requiring multiple tool calls and deep exploration +- **Realistic**: Based on real use cases humans would care about +- **Verifiable**: Single, clear answer that can be verified by string comparison +- **Stable**: Answer won't change over time + +#### 4.4 Output Format + +Create an XML file with this structure: + +```xml + + + Find discussions about AI model launches with animal codenames. One model needed a specific safety designation that uses the format ASL-X. What number X was being determined for the model named after a spotted wild cat? + 3 + + + +``` + +--- + +# Reference Files + +## 📚 Documentation Library + +Load these resources as needed during development: + +### Core MCP Documentation (Load First) +- **MCP Protocol**: Start with sitemap at `https://modelcontextprotocol.io/sitemap.xml`, then fetch specific pages with `.md` suffix +- [📋 MCP Best Practices](./references/mcp_best_practices.md) - Universal MCP guidelines including: + - Server and tool naming conventions + - Response format guidelines (JSON vs Markdown) + - Pagination best practices + - Transport selection (streamable HTTP vs stdio) + - Security and error handling standards + +### SDK Documentation (Load During Phase 1/2) +- **Python SDK**: Fetch from `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md` +- **TypeScript SDK**: Fetch from `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md` + +### Language-Specific Implementation Guides (Load During Phase 2) +- [🐍 Python Implementation Guide](./references/python_mcp_server.md) - Complete Python/FastMCP guide with: + - Server initialization patterns + - Pydantic model examples + - Tool registration with `@mcp.tool` + - Complete working examples + - Quality checklist + +- [⚡ TypeScript Implementation Guide](./references/node_mcp_server.md) - Complete TypeScript guide with: + - Project structure + - Zod schema patterns + - Tool registration with `server.registerTool` + - Complete working examples + - Quality checklist + +### Evaluation Guide (Load During Phase 4) +- [✅ Evaluation Guide](./references/evaluation.md) - Complete evaluation creation guide with: + - Question creation guidelines + - Answer verification strategies + - XML format specifications + - Example questions and answers + - Running an evaluation with the provided scripts diff --git a/contributing/samples/skill_script_demo/skills/mcp-builder/references/evaluation.md b/contributing/samples/skill_script_demo/skills/mcp-builder/references/evaluation.md new file mode 100644 index 0000000000..87e9bb7884 --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/mcp-builder/references/evaluation.md @@ -0,0 +1,602 @@ +# MCP Server Evaluation Guide + +## Overview + +This document provides guidance on creating comprehensive evaluations for MCP servers. Evaluations test whether LLMs can effectively use your MCP server to answer realistic, complex questions using only the tools provided. + +--- + +## Quick Reference + +### Evaluation Requirements +- Create 10 human-readable questions +- Questions must be READ-ONLY, INDEPENDENT, NON-DESTRUCTIVE +- Each question requires multiple tool calls (potentially dozens) +- Answers must be single, verifiable values +- Answers must be STABLE (won't change over time) + +### Output Format +```xml + + + Your question here + Single verifiable answer + + +``` + +--- + +## Purpose of Evaluations + +The measure of quality of an MCP server is NOT how well or comprehensively the server implements tools, but how well these implementations (input/output schemas, docstrings/descriptions, functionality) enable LLMs with no other context and access ONLY to the MCP servers to answer realistic and difficult questions. + +## Evaluation Overview + +Create 10 human-readable questions requiring ONLY READ-ONLY, INDEPENDENT, NON-DESTRUCTIVE, and IDEMPOTENT operations to answer. Each question should be: +- Realistic +- Clear and concise +- Unambiguous +- Complex, requiring potentially dozens of tool calls or steps +- Answerable with a single, verifiable value that you identify in advance + +## Question Guidelines + +### Core Requirements + +1. **Questions MUST be independent** + - Each question should NOT depend on the answer to any other question + - Should not assume prior write operations from processing another question + +2. **Questions MUST require ONLY NON-DESTRUCTIVE AND IDEMPOTENT tool use** + - Should not instruct or require modifying state to arrive at the correct answer + +3. **Questions must be REALISTIC, CLEAR, CONCISE, and COMPLEX** + - Must require another LLM to use multiple (potentially dozens of) tools or steps to answer + +### Complexity and Depth + +4. **Questions must require deep exploration** + - Consider multi-hop questions requiring multiple sub-questions and sequential tool calls + - Each step should benefit from information found in previous questions + +5. **Questions may require extensive paging** + - May need paging through multiple pages of results + - May require querying old data (1-2 years out-of-date) to find niche information + - The questions must be DIFFICULT + +6. **Questions must require deep understanding** + - Rather than surface-level knowledge + - May pose complex ideas as True/False questions requiring evidence + - May use multiple-choice format where LLM must search different hypotheses + +7. **Questions must not be solvable with straightforward keyword search** + - Do not include specific keywords from the target content + - Use synonyms, related concepts, or paraphrases + - Require multiple searches, analyzing multiple related items, extracting context, then deriving the answer + +### Tool Testing + +8. **Questions should stress-test tool return values** + - May elicit tools returning large JSON objects or lists, overwhelming the LLM + - Should require understanding multiple modalities of data: + - IDs and names + - Timestamps and datetimes (months, days, years, seconds) + - File IDs, names, extensions, and mimetypes + - URLs, GIDs, etc. + - Should probe the tool's ability to return all useful forms of data + +9. **Questions should MOSTLY reflect real human use cases** + - The kinds of information retrieval tasks that HUMANS assisted by an LLM would care about + +10. **Questions may require dozens of tool calls** + - This challenges LLMs with limited context + - Encourages MCP server tools to reduce information returned + +11. **Include ambiguous questions** + - May be ambiguous OR require difficult decisions on which tools to call + - Force the LLM to potentially make mistakes or misinterpret + - Ensure that despite AMBIGUITY, there is STILL A SINGLE VERIFIABLE ANSWER + +### Stability + +12. **Questions must be designed so the answer DOES NOT CHANGE** + - Do not ask questions that rely on "current state" which is dynamic + - For example, do not count: + - Number of reactions to a post + - Number of replies to a thread + - Number of members in a channel + +13. **DO NOT let the MCP server RESTRICT the kinds of questions you create** + - Create challenging and complex questions + - Some may not be solvable with the available MCP server tools + - Questions may require specific output formats (datetime vs. epoch time, JSON vs. MARKDOWN) + - Questions may require dozens of tool calls to complete + +## Answer Guidelines + +### Verification + +1. **Answers must be VERIFIABLE via direct string comparison** + - If the answer can be re-written in many formats, clearly specify the output format in the QUESTION + - Examples: "Use YYYY/MM/DD.", "Respond True or False.", "Answer A, B, C, or D and nothing else." + - Answer should be a single VERIFIABLE value such as: + - User ID, user name, display name, first name, last name + - Channel ID, channel name + - Message ID, string + - URL, title + - Numerical quantity + - Timestamp, datetime + - Boolean (for True/False questions) + - Email address, phone number + - File ID, file name, file extension + - Multiple choice answer + - Answers must not require special formatting or complex, structured output + - Answer will be verified using DIRECT STRING COMPARISON + +### Readability + +2. **Answers should generally prefer HUMAN-READABLE formats** + - Examples: names, first name, last name, datetime, file name, message string, URL, yes/no, true/false, a/b/c/d + - Rather than opaque IDs (though IDs are acceptable) + - The VAST MAJORITY of answers should be human-readable + +### Stability + +3. **Answers must be STABLE/STATIONARY** + - Look at old content (e.g., conversations that have ended, projects that have launched, questions answered) + - Create QUESTIONS based on "closed" concepts that will always return the same answer + - Questions may ask to consider a fixed time window to insulate from non-stationary answers + - Rely on context UNLIKELY to change + - Example: if finding a paper name, be SPECIFIC enough so answer is not confused with papers published later + +4. **Answers must be CLEAR and UNAMBIGUOUS** + - Questions must be designed so there is a single, clear answer + - Answer can be derived from using the MCP server tools + +### Diversity + +5. **Answers must be DIVERSE** + - Answer should be a single VERIFIABLE value in diverse modalities and formats + - User concept: user ID, user name, display name, first name, last name, email address, phone number + - Channel concept: channel ID, channel name, channel topic + - Message concept: message ID, message string, timestamp, month, day, year + +6. **Answers must NOT be complex structures** + - Not a list of values + - Not a complex object + - Not a list of IDs or strings + - Not natural language text + - UNLESS the answer can be straightforwardly verified using DIRECT STRING COMPARISON + - And can be realistically reproduced + - It should be unlikely that an LLM would return the same list in any other order or format + +## Evaluation Process + +### Step 1: Documentation Inspection + +Read the documentation of the target API to understand: +- Available endpoints and functionality +- If ambiguity exists, fetch additional information from the web +- Parallelize this step AS MUCH AS POSSIBLE +- Ensure each subagent is ONLY examining documentation from the file system or on the web + +### Step 2: Tool Inspection + +List the tools available in the MCP server: +- Inspect the MCP server directly +- Understand input/output schemas, docstrings, and descriptions +- WITHOUT calling the tools themselves at this stage + +### Step 3: Developing Understanding + +Repeat steps 1 & 2 until you have a good understanding: +- Iterate multiple times +- Think about the kinds of tasks you want to create +- Refine your understanding +- At NO stage should you READ the code of the MCP server implementation itself +- Use your intuition and understanding to create reasonable, realistic, but VERY challenging tasks + +### Step 4: Read-Only Content Inspection + +After understanding the API and tools, USE the MCP server tools: +- Inspect content using READ-ONLY and NON-DESTRUCTIVE operations ONLY +- Goal: identify specific content (e.g., users, channels, messages, projects, tasks) for creating realistic questions +- Should NOT call any tools that modify state +- Will NOT read the code of the MCP server implementation itself +- Parallelize this step with individual sub-agents pursuing independent explorations +- Ensure each subagent is only performing READ-ONLY, NON-DESTRUCTIVE, and IDEMPOTENT operations +- BE CAREFUL: SOME TOOLS may return LOTS OF DATA which would cause you to run out of CONTEXT +- Make INCREMENTAL, SMALL, AND TARGETED tool calls for exploration +- In all tool call requests, use the `limit` parameter to limit results (<10) +- Use pagination + +### Step 5: Task Generation + +After inspecting the content, create 10 human-readable questions: +- An LLM should be able to answer these with the MCP server +- Follow all question and answer guidelines above + +## Output Format + +Each QA pair consists of a question and an answer. The output should be an XML file with this structure: + +```xml + + + Find the project created in Q2 2024 with the highest number of completed tasks. What is the project name? + Website Redesign + + + Search for issues labeled as "bug" that were closed in March 2024. Which user closed the most issues? Provide their username. + sarah_dev + + + Look for pull requests that modified files in the /api directory and were merged between January 1 and January 31, 2024. How many different contributors worked on these PRs? + 7 + + + Find the repository with the most stars that was created before 2023. What is the repository name? + data-pipeline + + +``` + +## Evaluation Examples + +### Good Questions + +**Example 1: Multi-hop question requiring deep exploration (GitHub MCP)** +```xml + + Find the repository that was archived in Q3 2023 and had previously been the most forked project in the organization. What was the primary programming language used in that repository? + Python + +``` + +This question is good because: +- Requires multiple searches to find archived repositories +- Needs to identify which had the most forks before archival +- Requires examining repository details for the language +- Answer is a simple, verifiable value +- Based on historical (closed) data that won't change + +**Example 2: Requires understanding context without keyword matching (Project Management MCP)** +```xml + + Locate the initiative focused on improving customer onboarding that was completed in late 2023. The project lead created a retrospective document after completion. What was the lead's role title at that time? + Product Manager + +``` + +This question is good because: +- Doesn't use specific project name ("initiative focused on improving customer onboarding") +- Requires finding completed projects from specific timeframe +- Needs to identify the project lead and their role +- Requires understanding context from retrospective documents +- Answer is human-readable and stable +- Based on completed work (won't change) + +**Example 3: Complex aggregation requiring multiple steps (Issue Tracker MCP)** +```xml + + Among all bugs reported in January 2024 that were marked as critical priority, which assignee resolved the highest percentage of their assigned bugs within 48 hours? Provide the assignee's username. + alex_eng + +``` + +This question is good because: +- Requires filtering bugs by date, priority, and status +- Needs to group by assignee and calculate resolution rates +- Requires understanding timestamps to determine 48-hour windows +- Tests pagination (potentially many bugs to process) +- Answer is a single username +- Based on historical data from specific time period + +**Example 4: Requires synthesis across multiple data types (CRM MCP)** +```xml + + Find the account that upgraded from the Starter to Enterprise plan in Q4 2023 and had the highest annual contract value. What industry does this account operate in? + Healthcare + +``` + +This question is good because: +- Requires understanding subscription tier changes +- Needs to identify upgrade events in specific timeframe +- Requires comparing contract values +- Must access account industry information +- Answer is simple and verifiable +- Based on completed historical transactions + +### Poor Questions + +**Example 1: Answer changes over time** +```xml + + How many open issues are currently assigned to the engineering team? + 47 + +``` + +This question is poor because: +- The answer will change as issues are created, closed, or reassigned +- Not based on stable/stationary data +- Relies on "current state" which is dynamic + +**Example 2: Too easy with keyword search** +```xml + + Find the pull request with title "Add authentication feature" and tell me who created it. + developer123 + +``` + +This question is poor because: +- Can be solved with a straightforward keyword search for exact title +- Doesn't require deep exploration or understanding +- No synthesis or analysis needed + +**Example 3: Ambiguous answer format** +```xml + + List all the repositories that have Python as their primary language. + repo1, repo2, repo3, data-pipeline, ml-tools + +``` + +This question is poor because: +- Answer is a list that could be returned in any order +- Difficult to verify with direct string comparison +- LLM might format differently (JSON array, comma-separated, newline-separated) +- Better to ask for a specific aggregate (count) or superlative (most stars) + +## Verification Process + +After creating evaluations: + +1. **Examine the XML file** to understand the schema +2. **Load each task instruction** and in parallel using the MCP server and tools, identify the correct answer by attempting to solve the task YOURSELF +3. **Flag any operations** that require WRITE or DESTRUCTIVE operations +4. **Accumulate all CORRECT answers** and replace any incorrect answers in the document +5. **Remove any ``** that require WRITE or DESTRUCTIVE operations + +Remember to parallelize solving tasks to avoid running out of context, then accumulate all answers and make changes to the file at the end. + +## Tips for Creating Quality Evaluations + +1. **Think Hard and Plan Ahead** before generating tasks +2. **Parallelize Where Opportunity Arises** to speed up the process and manage context +3. **Focus on Realistic Use Cases** that humans would actually want to accomplish +4. **Create Challenging Questions** that test the limits of the MCP server's capabilities +5. **Ensure Stability** by using historical data and closed concepts +6. **Verify Answers** by solving the questions yourself using the MCP server tools +7. **Iterate and Refine** based on what you learn during the process + +--- + +# Running Evaluations + +After creating your evaluation file, you can use the provided evaluation harness to test your MCP server. + +## Setup + +1. **Install Dependencies** + + ```bash + pip install -r scripts/requirements.txt + ``` + + Or install manually: + ```bash + pip install anthropic mcp + ``` + +2. **Set API Key** + + ```bash + export ANTHROPIC_API_KEY=your_api_key_here + ``` + +## Evaluation File Format + +Evaluation files use XML format with `` elements: + +```xml + + + Find the project created in Q2 2024 with the highest number of completed tasks. What is the project name? + Website Redesign + + + Search for issues labeled as "bug" that were closed in March 2024. Which user closed the most issues? Provide their username. + sarah_dev + + +``` + +## Running Evaluations + +The evaluation script (`scripts/evaluation.py`) supports three transport types: + +**Important:** +- **stdio transport**: The evaluation script automatically launches and manages the MCP server process for you. Do not run the server manually. +- **sse/http transports**: You must start the MCP server separately before running the evaluation. The script connects to the already-running server at the specified URL. + +### 1. Local STDIO Server + +For locally-run MCP servers (script launches the server automatically): + +```bash +python scripts/evaluation.py \ + -t stdio \ + -c python \ + -a my_mcp_server.py \ + evaluation.xml +``` + +With environment variables: +```bash +python scripts/evaluation.py \ + -t stdio \ + -c python \ + -a my_mcp_server.py \ + -e API_KEY=abc123 \ + -e DEBUG=true \ + evaluation.xml +``` + +### 2. Server-Sent Events (SSE) + +For SSE-based MCP servers (you must start the server first): + +```bash +python scripts/evaluation.py \ + -t sse \ + -u https://example.com/mcp \ + -H "Authorization: Bearer token123" \ + -H "X-Custom-Header: value" \ + evaluation.xml +``` + +### 3. HTTP (Streamable HTTP) + +For HTTP-based MCP servers (you must start the server first): + +```bash +python scripts/evaluation.py \ + -t http \ + -u https://example.com/mcp \ + -H "Authorization: Bearer token123" \ + evaluation.xml +``` + +## Command-Line Options + +``` +usage: evaluation.py [-h] [-t {stdio,sse,http}] [-m MODEL] [-c COMMAND] + [-a ARGS [ARGS ...]] [-e ENV [ENV ...]] [-u URL] + [-H HEADERS [HEADERS ...]] [-o OUTPUT] + eval_file + +positional arguments: + eval_file Path to evaluation XML file + +optional arguments: + -h, --help Show help message + -t, --transport Transport type: stdio, sse, or http (default: stdio) + -m, --model Claude model to use (default: claude-3-7-sonnet-20250219) + -o, --output Output file for report (default: print to stdout) + +stdio options: + -c, --command Command to run MCP server (e.g., python, node) + -a, --args Arguments for the command (e.g., server.py) + -e, --env Environment variables in KEY=VALUE format + +sse/http options: + -u, --url MCP server URL + -H, --header HTTP headers in 'Key: Value' format +``` + +## Output + +The evaluation script generates a detailed report including: + +- **Summary Statistics**: + - Accuracy (correct/total) + - Average task duration + - Average tool calls per task + - Total tool calls + +- **Per-Task Results**: + - Prompt and expected response + - Actual response from the agent + - Whether the answer was correct (✅/❌) + - Duration and tool call details + - Agent's summary of its approach + - Agent's feedback on the tools + +### Save Report to File + +```bash +python scripts/evaluation.py \ + -t stdio \ + -c python \ + -a my_server.py \ + -o evaluation_report.md \ + evaluation.xml +``` + +## Complete Example Workflow + +Here's a complete example of creating and running an evaluation: + +1. **Create your evaluation file** (`my_evaluation.xml`): + +```xml + + + Find the user who created the most issues in January 2024. What is their username? + alice_developer + + + Among all pull requests merged in Q1 2024, which repository had the highest number? Provide the repository name. + backend-api + + + Find the project that was completed in December 2023 and had the longest duration from start to finish. How many days did it take? + 127 + + +``` + +2. **Install dependencies**: + +```bash +pip install -r scripts/requirements.txt +export ANTHROPIC_API_KEY=your_api_key +``` + +3. **Run evaluation**: + +```bash +python scripts/evaluation.py \ + -t stdio \ + -c python \ + -a github_mcp_server.py \ + -e GITHUB_TOKEN=ghp_xxx \ + -o github_eval_report.md \ + my_evaluation.xml +``` + +4. **Review the report** in `github_eval_report.md` to: + - See which questions passed/failed + - Read the agent's feedback on your tools + - Identify areas for improvement + - Iterate on your MCP server design + +## Troubleshooting + +### Connection Errors + +If you get connection errors: +- **STDIO**: Verify the command and arguments are correct +- **SSE/HTTP**: Check the URL is accessible and headers are correct +- Ensure any required API keys are set in environment variables or headers + +### Low Accuracy + +If many evaluations fail: +- Review the agent's feedback for each task +- Check if tool descriptions are clear and comprehensive +- Verify input parameters are well-documented +- Consider whether tools return too much or too little data +- Ensure error messages are actionable + +### Timeout Issues + +If tasks are timing out: +- Use a more capable model (e.g., `claude-3-7-sonnet-20250219`) +- Check if tools are returning too much data +- Verify pagination is working correctly +- Consider simplifying complex questions \ No newline at end of file diff --git a/contributing/samples/skill_script_demo/skills/mcp-builder/references/mcp_best_practices.md b/contributing/samples/skill_script_demo/skills/mcp-builder/references/mcp_best_practices.md new file mode 100644 index 0000000000..b9d343cc3a --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/mcp-builder/references/mcp_best_practices.md @@ -0,0 +1,249 @@ +# MCP Server Best Practices + +## Quick Reference + +### Server Naming +- **Python**: `{service}_mcp` (e.g., `slack_mcp`) +- **Node/TypeScript**: `{service}-mcp-server` (e.g., `slack-mcp-server`) + +### Tool Naming +- Use snake_case with service prefix +- Format: `{service}_{action}_{resource}` +- Example: `slack_send_message`, `github_create_issue` + +### Response Formats +- Support both JSON and Markdown formats +- JSON for programmatic processing +- Markdown for human readability + +### Pagination +- Always respect `limit` parameter +- Return `has_more`, `next_offset`, `total_count` +- Default to 20-50 items + +### Transport +- **Streamable HTTP**: For remote servers, multi-client scenarios +- **stdio**: For local integrations, command-line tools +- Avoid SSE (deprecated in favor of streamable HTTP) + +--- + +## Server Naming Conventions + +Follow these standardized naming patterns: + +**Python**: Use format `{service}_mcp` (lowercase with underscores) +- Examples: `slack_mcp`, `github_mcp`, `jira_mcp` + +**Node/TypeScript**: Use format `{service}-mcp-server` (lowercase with hyphens) +- Examples: `slack-mcp-server`, `github-mcp-server`, `jira-mcp-server` + +The name should be general, descriptive of the service being integrated, easy to infer from the task description, and without version numbers. + +--- + +## Tool Naming and Design + +### Tool Naming + +1. **Use snake_case**: `search_users`, `create_project`, `get_channel_info` +2. **Include service prefix**: Anticipate that your MCP server may be used alongside other MCP servers + - Use `slack_send_message` instead of just `send_message` + - Use `github_create_issue` instead of just `create_issue` +3. **Be action-oriented**: Start with verbs (get, list, search, create, etc.) +4. **Be specific**: Avoid generic names that could conflict with other servers + +### Tool Design + +- Tool descriptions must narrowly and unambiguously describe functionality +- Descriptions must precisely match actual functionality +- Provide tool annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint) +- Keep tool operations focused and atomic + +--- + +## Response Formats + +All tools that return data should support multiple formats: + +### JSON Format (`response_format="json"`) +- Machine-readable structured data +- Include all available fields and metadata +- Consistent field names and types +- Use for programmatic processing + +### Markdown Format (`response_format="markdown"`, typically default) +- Human-readable formatted text +- Use headers, lists, and formatting for clarity +- Convert timestamps to human-readable format +- Show display names with IDs in parentheses +- Omit verbose metadata + +--- + +## Pagination + +For tools that list resources: + +- **Always respect the `limit` parameter** +- **Implement pagination**: Use `offset` or cursor-based pagination +- **Return pagination metadata**: Include `has_more`, `next_offset`/`next_cursor`, `total_count` +- **Never load all results into memory**: Especially important for large datasets +- **Default to reasonable limits**: 20-50 items is typical + +Example pagination response: +```json +{ + "total": 150, + "count": 20, + "offset": 0, + "items": [...], + "has_more": true, + "next_offset": 20 +} +``` + +--- + +## Transport Options + +### Streamable HTTP + +**Best for**: Remote servers, web services, multi-client scenarios + +**Characteristics**: +- Bidirectional communication over HTTP +- Supports multiple simultaneous clients +- Can be deployed as a web service +- Enables server-to-client notifications + +**Use when**: +- Serving multiple clients simultaneously +- Deploying as a cloud service +- Integration with web applications + +### stdio + +**Best for**: Local integrations, command-line tools + +**Characteristics**: +- Standard input/output stream communication +- Simple setup, no network configuration needed +- Runs as a subprocess of the client + +**Use when**: +- Building tools for local development environments +- Integrating with desktop applications +- Single-user, single-session scenarios + +**Note**: stdio servers should NOT log to stdout (use stderr for logging) + +### Transport Selection + +| Criterion | stdio | Streamable HTTP | +|-----------|-------|-----------------| +| **Deployment** | Local | Remote | +| **Clients** | Single | Multiple | +| **Complexity** | Low | Medium | +| **Real-time** | No | Yes | + +--- + +## Security Best Practices + +### Authentication and Authorization + +**OAuth 2.1**: +- Use secure OAuth 2.1 with certificates from recognized authorities +- Validate access tokens before processing requests +- Only accept tokens specifically intended for your server + +**API Keys**: +- Store API keys in environment variables, never in code +- Validate keys on server startup +- Provide clear error messages when authentication fails + +### Input Validation + +- Sanitize file paths to prevent directory traversal +- Validate URLs and external identifiers +- Check parameter sizes and ranges +- Prevent command injection in system calls +- Use schema validation (Pydantic/Zod) for all inputs + +### Error Handling + +- Don't expose internal errors to clients +- Log security-relevant errors server-side +- Provide helpful but not revealing error messages +- Clean up resources after errors + +### DNS Rebinding Protection + +For streamable HTTP servers running locally: +- Enable DNS rebinding protection +- Validate the `Origin` header on all incoming connections +- Bind to `127.0.0.1` rather than `0.0.0.0` + +--- + +## Tool Annotations + +Provide annotations to help clients understand tool behavior: + +| Annotation | Type | Default | Description | +|-----------|------|---------|-------------| +| `readOnlyHint` | boolean | false | Tool does not modify its environment | +| `destructiveHint` | boolean | true | Tool may perform destructive updates | +| `idempotentHint` | boolean | false | Repeated calls with same args have no additional effect | +| `openWorldHint` | boolean | true | Tool interacts with external entities | + +**Important**: Annotations are hints, not security guarantees. Clients should not make security-critical decisions based solely on annotations. + +--- + +## Error Handling + +- Use standard JSON-RPC error codes +- Report tool errors within result objects (not protocol-level errors) +- Provide helpful, specific error messages with suggested next steps +- Don't expose internal implementation details +- Clean up resources properly on errors + +Example error handling: +```typescript +try { + const result = performOperation(); + return { content: [{ type: "text", text: result }] }; +} catch (error) { + return { + isError: true, + content: [{ + type: "text", + text: `Error: ${error.message}. Try using filter='active_only' to reduce results.` + }] + }; +} +``` + +--- + +## Testing Requirements + +Comprehensive testing should cover: + +- **Functional testing**: Verify correct execution with valid/invalid inputs +- **Integration testing**: Test interaction with external systems +- **Security testing**: Validate auth, input sanitization, rate limiting +- **Performance testing**: Check behavior under load, timeouts +- **Error handling**: Ensure proper error reporting and cleanup + +--- + +## Documentation Requirements + +- Provide clear documentation of all tools and capabilities +- Include working examples (at least 3 per major feature) +- Document security considerations +- Specify required permissions and access levels +- Document rate limits and performance characteristics diff --git a/contributing/samples/skill_script_demo/skills/mcp-builder/references/node_mcp_server.md b/contributing/samples/skill_script_demo/skills/mcp-builder/references/node_mcp_server.md new file mode 100644 index 0000000000..f6e5df982a --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/mcp-builder/references/node_mcp_server.md @@ -0,0 +1,970 @@ +# Node/TypeScript MCP Server Implementation Guide + +## Overview + +This document provides Node/TypeScript-specific best practices and examples for implementing MCP servers using the MCP TypeScript SDK. It covers project structure, server setup, tool registration patterns, input validation with Zod, error handling, and complete working examples. + +--- + +## Quick Reference + +### Key Imports +```typescript +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import express from "express"; +import { z } from "zod"; +``` + +### Server Initialization +```typescript +const server = new McpServer({ + name: "service-mcp-server", + version: "1.0.0" +}); +``` + +### Tool Registration Pattern +```typescript +server.registerTool( + "tool_name", + { + title: "Tool Display Name", + description: "What the tool does", + inputSchema: { param: z.string() }, + outputSchema: { result: z.string() } + }, + async ({ param }) => { + const output = { result: `Processed: ${param}` }; + return { + content: [{ type: "text", text: JSON.stringify(output) }], + structuredContent: output // Modern pattern for structured data + }; + } +); +``` + +--- + +## MCP TypeScript SDK + +The official MCP TypeScript SDK provides: +- `McpServer` class for server initialization +- `registerTool` method for tool registration +- Zod schema integration for runtime input validation +- Type-safe tool handler implementations + +**IMPORTANT - Use Modern APIs Only:** +- **DO use**: `server.registerTool()`, `server.registerResource()`, `server.registerPrompt()` +- **DO NOT use**: Old deprecated APIs such as `server.tool()`, `server.setRequestHandler(ListToolsRequestSchema, ...)`, or manual handler registration +- The `register*` methods provide better type safety, automatic schema handling, and are the recommended approach + +See the MCP SDK documentation in the references for complete details. + +## Server Naming Convention + +Node/TypeScript MCP servers must follow this naming pattern: +- **Format**: `{service}-mcp-server` (lowercase with hyphens) +- **Examples**: `github-mcp-server`, `jira-mcp-server`, `stripe-mcp-server` + +The name should be: +- General (not tied to specific features) +- Descriptive of the service/API being integrated +- Easy to infer from the task description +- Without version numbers or dates + +## Project Structure + +Create the following structure for Node/TypeScript MCP servers: + +``` +{service}-mcp-server/ +├── package.json +├── tsconfig.json +├── README.md +├── src/ +│ ├── index.ts # Main entry point with McpServer initialization +│ ├── types.ts # TypeScript type definitions and interfaces +│ ├── tools/ # Tool implementations (one file per domain) +│ ├── services/ # API clients and shared utilities +│ ├── schemas/ # Zod validation schemas +│ └── constants.ts # Shared constants (API_URL, CHARACTER_LIMIT, etc.) +└── dist/ # Built JavaScript files (entry point: dist/index.js) +``` + +## Tool Implementation + +### Tool Naming + +Use snake_case for tool names (e.g., "search_users", "create_project", "get_channel_info") with clear, action-oriented names. + +**Avoid Naming Conflicts**: Include the service context to prevent overlaps: +- Use "slack_send_message" instead of just "send_message" +- Use "github_create_issue" instead of just "create_issue" +- Use "asana_list_tasks" instead of just "list_tasks" + +### Tool Structure + +Tools are registered using the `registerTool` method with the following requirements: +- Use Zod schemas for runtime input validation and type safety +- The `description` field must be explicitly provided - JSDoc comments are NOT automatically extracted +- Explicitly provide `title`, `description`, `inputSchema`, and `annotations` +- The `inputSchema` must be a Zod schema object (not a JSON schema) +- Type all parameters and return values explicitly + +```typescript +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { z } from "zod"; + +const server = new McpServer({ + name: "example-mcp", + version: "1.0.0" +}); + +// Zod schema for input validation +const UserSearchInputSchema = z.object({ + query: z.string() + .min(2, "Query must be at least 2 characters") + .max(200, "Query must not exceed 200 characters") + .describe("Search string to match against names/emails"), + limit: z.number() + .int() + .min(1) + .max(100) + .default(20) + .describe("Maximum results to return"), + offset: z.number() + .int() + .min(0) + .default(0) + .describe("Number of results to skip for pagination"), + response_format: z.nativeEnum(ResponseFormat) + .default(ResponseFormat.MARKDOWN) + .describe("Output format: 'markdown' for human-readable or 'json' for machine-readable") +}).strict(); + +// Type definition from Zod schema +type UserSearchInput = z.infer; + +server.registerTool( + "example_search_users", + { + title: "Search Example Users", + description: `Search for users in the Example system by name, email, or team. + +This tool searches across all user profiles in the Example platform, supporting partial matches and various search filters. It does NOT create or modify users, only searches existing ones. + +Args: + - query (string): Search string to match against names/emails + - limit (number): Maximum results to return, between 1-100 (default: 20) + - offset (number): Number of results to skip for pagination (default: 0) + - response_format ('markdown' | 'json'): Output format (default: 'markdown') + +Returns: + For JSON format: Structured data with schema: + { + "total": number, // Total number of matches found + "count": number, // Number of results in this response + "offset": number, // Current pagination offset + "users": [ + { + "id": string, // User ID (e.g., "U123456789") + "name": string, // Full name (e.g., "John Doe") + "email": string, // Email address + "team": string, // Team name (optional) + "active": boolean // Whether user is active + } + ], + "has_more": boolean, // Whether more results are available + "next_offset": number // Offset for next page (if has_more is true) + } + +Examples: + - Use when: "Find all marketing team members" -> params with query="team:marketing" + - Use when: "Search for John's account" -> params with query="john" + - Don't use when: You need to create a user (use example_create_user instead) + +Error Handling: + - Returns "Error: Rate limit exceeded" if too many requests (429 status) + - Returns "No users found matching ''" if search returns empty`, + inputSchema: UserSearchInputSchema, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: true + } + }, + async (params: UserSearchInput) => { + try { + // Input validation is handled by Zod schema + // Make API request using validated parameters + const data = await makeApiRequest( + "users/search", + "GET", + undefined, + { + q: params.query, + limit: params.limit, + offset: params.offset + } + ); + + const users = data.users || []; + const total = data.total || 0; + + if (!users.length) { + return { + content: [{ + type: "text", + text: `No users found matching '${params.query}'` + }] + }; + } + + // Prepare structured output + const output = { + total, + count: users.length, + offset: params.offset, + users: users.map((user: any) => ({ + id: user.id, + name: user.name, + email: user.email, + ...(user.team ? { team: user.team } : {}), + active: user.active ?? true + })), + has_more: total > params.offset + users.length, + ...(total > params.offset + users.length ? { + next_offset: params.offset + users.length + } : {}) + }; + + // Format text representation based on requested format + let textContent: string; + if (params.response_format === ResponseFormat.MARKDOWN) { + const lines = [`# User Search Results: '${params.query}'`, "", + `Found ${total} users (showing ${users.length})`, ""]; + for (const user of users) { + lines.push(`## ${user.name} (${user.id})`); + lines.push(`- **Email**: ${user.email}`); + if (user.team) lines.push(`- **Team**: ${user.team}`); + lines.push(""); + } + textContent = lines.join("\n"); + } else { + textContent = JSON.stringify(output, null, 2); + } + + return { + content: [{ type: "text", text: textContent }], + structuredContent: output // Modern pattern for structured data + }; + } catch (error) { + return { + content: [{ + type: "text", + text: handleApiError(error) + }] + }; + } + } +); +``` + +## Zod Schemas for Input Validation + +Zod provides runtime type validation: + +```typescript +import { z } from "zod"; + +// Basic schema with validation +const CreateUserSchema = z.object({ + name: z.string() + .min(1, "Name is required") + .max(100, "Name must not exceed 100 characters"), + email: z.string() + .email("Invalid email format"), + age: z.number() + .int("Age must be a whole number") + .min(0, "Age cannot be negative") + .max(150, "Age cannot be greater than 150") +}).strict(); // Use .strict() to forbid extra fields + +// Enums +enum ResponseFormat { + MARKDOWN = "markdown", + JSON = "json" +} + +const SearchSchema = z.object({ + response_format: z.nativeEnum(ResponseFormat) + .default(ResponseFormat.MARKDOWN) + .describe("Output format") +}); + +// Optional fields with defaults +const PaginationSchema = z.object({ + limit: z.number() + .int() + .min(1) + .max(100) + .default(20) + .describe("Maximum results to return"), + offset: z.number() + .int() + .min(0) + .default(0) + .describe("Number of results to skip") +}); +``` + +## Response Format Options + +Support multiple output formats for flexibility: + +```typescript +enum ResponseFormat { + MARKDOWN = "markdown", + JSON = "json" +} + +const inputSchema = z.object({ + query: z.string(), + response_format: z.nativeEnum(ResponseFormat) + .default(ResponseFormat.MARKDOWN) + .describe("Output format: 'markdown' for human-readable or 'json' for machine-readable") +}); +``` + +**Markdown format**: +- Use headers, lists, and formatting for clarity +- Convert timestamps to human-readable format +- Show display names with IDs in parentheses +- Omit verbose metadata +- Group related information logically + +**JSON format**: +- Return complete, structured data suitable for programmatic processing +- Include all available fields and metadata +- Use consistent field names and types + +## Pagination Implementation + +For tools that list resources: + +```typescript +const ListSchema = z.object({ + limit: z.number().int().min(1).max(100).default(20), + offset: z.number().int().min(0).default(0) +}); + +async function listItems(params: z.infer) { + const data = await apiRequest(params.limit, params.offset); + + const response = { + total: data.total, + count: data.items.length, + offset: params.offset, + items: data.items, + has_more: data.total > params.offset + data.items.length, + next_offset: data.total > params.offset + data.items.length + ? params.offset + data.items.length + : undefined + }; + + return JSON.stringify(response, null, 2); +} +``` + +## Character Limits and Truncation + +Add a CHARACTER_LIMIT constant to prevent overwhelming responses: + +```typescript +// At module level in constants.ts +export const CHARACTER_LIMIT = 25000; // Maximum response size in characters + +async function searchTool(params: SearchInput) { + let result = generateResponse(data); + + // Check character limit and truncate if needed + if (result.length > CHARACTER_LIMIT) { + const truncatedData = data.slice(0, Math.max(1, data.length / 2)); + response.data = truncatedData; + response.truncated = true; + response.truncation_message = + `Response truncated from ${data.length} to ${truncatedData.length} items. ` + + `Use 'offset' parameter or add filters to see more results.`; + result = JSON.stringify(response, null, 2); + } + + return result; +} +``` + +## Error Handling + +Provide clear, actionable error messages: + +```typescript +import axios, { AxiosError } from "axios"; + +function handleApiError(error: unknown): string { + if (error instanceof AxiosError) { + if (error.response) { + switch (error.response.status) { + case 404: + return "Error: Resource not found. Please check the ID is correct."; + case 403: + return "Error: Permission denied. You don't have access to this resource."; + case 429: + return "Error: Rate limit exceeded. Please wait before making more requests."; + default: + return `Error: API request failed with status ${error.response.status}`; + } + } else if (error.code === "ECONNABORTED") { + return "Error: Request timed out. Please try again."; + } + } + return `Error: Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`; +} +``` + +## Shared Utilities + +Extract common functionality into reusable functions: + +```typescript +// Shared API request function +async function makeApiRequest( + endpoint: string, + method: "GET" | "POST" | "PUT" | "DELETE" = "GET", + data?: any, + params?: any +): Promise { + try { + const response = await axios({ + method, + url: `${API_BASE_URL}/${endpoint}`, + data, + params, + timeout: 30000, + headers: { + "Content-Type": "application/json", + "Accept": "application/json" + } + }); + return response.data; + } catch (error) { + throw error; + } +} +``` + +## Async/Await Best Practices + +Always use async/await for network requests and I/O operations: + +```typescript +// Good: Async network request +async function fetchData(resourceId: string): Promise { + const response = await axios.get(`${API_URL}/resource/${resourceId}`); + return response.data; +} + +// Bad: Promise chains +function fetchData(resourceId: string): Promise { + return axios.get(`${API_URL}/resource/${resourceId}`) + .then(response => response.data); // Harder to read and maintain +} +``` + +## TypeScript Best Practices + +1. **Use Strict TypeScript**: Enable strict mode in tsconfig.json +2. **Define Interfaces**: Create clear interface definitions for all data structures +3. **Avoid `any`**: Use proper types or `unknown` instead of `any` +4. **Zod for Runtime Validation**: Use Zod schemas to validate external data +5. **Type Guards**: Create type guard functions for complex type checking +6. **Error Handling**: Always use try-catch with proper error type checking +7. **Null Safety**: Use optional chaining (`?.`) and nullish coalescing (`??`) + +```typescript +// Good: Type-safe with Zod and interfaces +interface UserResponse { + id: string; + name: string; + email: string; + team?: string; + active: boolean; +} + +const UserSchema = z.object({ + id: z.string(), + name: z.string(), + email: z.string().email(), + team: z.string().optional(), + active: z.boolean() +}); + +type User = z.infer; + +async function getUser(id: string): Promise { + const data = await apiCall(`/users/${id}`); + return UserSchema.parse(data); // Runtime validation +} + +// Bad: Using any +async function getUser(id: string): Promise { + return await apiCall(`/users/${id}`); // No type safety +} +``` + +## Package Configuration + +### package.json + +```json +{ + "name": "{service}-mcp-server", + "version": "1.0.0", + "description": "MCP server for {Service} API integration", + "type": "module", + "main": "dist/index.js", + "scripts": { + "start": "node dist/index.js", + "dev": "tsx watch src/index.ts", + "build": "tsc", + "clean": "rm -rf dist" + }, + "engines": { + "node": ">=18" + }, + "dependencies": { + "@modelcontextprotocol/sdk": "^1.6.1", + "axios": "^1.7.9", + "zod": "^3.23.8" + }, + "devDependencies": { + "@types/node": "^22.10.0", + "tsx": "^4.19.2", + "typescript": "^5.7.2" + } +} +``` + +### tsconfig.json + +```json +{ + "compilerOptions": { + "target": "ES2022", + "module": "Node16", + "moduleResolution": "Node16", + "lib": ["ES2022"], + "outDir": "./dist", + "rootDir": "./src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "allowSyntheticDefaultImports": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} +``` + +## Complete Example + +```typescript +#!/usr/bin/env node +/** + * MCP Server for Example Service. + * + * This server provides tools to interact with Example API, including user search, + * project management, and data export capabilities. + */ + +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import { z } from "zod"; +import axios, { AxiosError } from "axios"; + +// Constants +const API_BASE_URL = "https://api.example.com/v1"; +const CHARACTER_LIMIT = 25000; + +// Enums +enum ResponseFormat { + MARKDOWN = "markdown", + JSON = "json" +} + +// Zod schemas +const UserSearchInputSchema = z.object({ + query: z.string() + .min(2, "Query must be at least 2 characters") + .max(200, "Query must not exceed 200 characters") + .describe("Search string to match against names/emails"), + limit: z.number() + .int() + .min(1) + .max(100) + .default(20) + .describe("Maximum results to return"), + offset: z.number() + .int() + .min(0) + .default(0) + .describe("Number of results to skip for pagination"), + response_format: z.nativeEnum(ResponseFormat) + .default(ResponseFormat.MARKDOWN) + .describe("Output format: 'markdown' for human-readable or 'json' for machine-readable") +}).strict(); + +type UserSearchInput = z.infer; + +// Shared utility functions +async function makeApiRequest( + endpoint: string, + method: "GET" | "POST" | "PUT" | "DELETE" = "GET", + data?: any, + params?: any +): Promise { + try { + const response = await axios({ + method, + url: `${API_BASE_URL}/${endpoint}`, + data, + params, + timeout: 30000, + headers: { + "Content-Type": "application/json", + "Accept": "application/json" + } + }); + return response.data; + } catch (error) { + throw error; + } +} + +function handleApiError(error: unknown): string { + if (error instanceof AxiosError) { + if (error.response) { + switch (error.response.status) { + case 404: + return "Error: Resource not found. Please check the ID is correct."; + case 403: + return "Error: Permission denied. You don't have access to this resource."; + case 429: + return "Error: Rate limit exceeded. Please wait before making more requests."; + default: + return `Error: API request failed with status ${error.response.status}`; + } + } else if (error.code === "ECONNABORTED") { + return "Error: Request timed out. Please try again."; + } + } + return `Error: Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`; +} + +// Create MCP server instance +const server = new McpServer({ + name: "example-mcp", + version: "1.0.0" +}); + +// Register tools +server.registerTool( + "example_search_users", + { + title: "Search Example Users", + description: `[Full description as shown above]`, + inputSchema: UserSearchInputSchema, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: true + } + }, + async (params: UserSearchInput) => { + // Implementation as shown above + } +); + +// Main function +// For stdio (local): +async function runStdio() { + if (!process.env.EXAMPLE_API_KEY) { + console.error("ERROR: EXAMPLE_API_KEY environment variable is required"); + process.exit(1); + } + + const transport = new StdioServerTransport(); + await server.connect(transport); + console.error("MCP server running via stdio"); +} + +// For streamable HTTP (remote): +async function runHTTP() { + if (!process.env.EXAMPLE_API_KEY) { + console.error("ERROR: EXAMPLE_API_KEY environment variable is required"); + process.exit(1); + } + + const app = express(); + app.use(express.json()); + + app.post('/mcp', async (req, res) => { + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + enableJsonResponse: true + }); + res.on('close', () => transport.close()); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + }); + + const port = parseInt(process.env.PORT || '3000'); + app.listen(port, () => { + console.error(`MCP server running on http://localhost:${port}/mcp`); + }); +} + +// Choose transport based on environment +const transport = process.env.TRANSPORT || 'stdio'; +if (transport === 'http') { + runHTTP().catch(error => { + console.error("Server error:", error); + process.exit(1); + }); +} else { + runStdio().catch(error => { + console.error("Server error:", error); + process.exit(1); + }); +} +``` + +--- + +## Advanced MCP Features + +### Resource Registration + +Expose data as resources for efficient, URI-based access: + +```typescript +import { ResourceTemplate } from "@modelcontextprotocol/sdk/types.js"; + +// Register a resource with URI template +server.registerResource( + { + uri: "file://documents/{name}", + name: "Document Resource", + description: "Access documents by name", + mimeType: "text/plain" + }, + async (uri: string) => { + // Extract parameter from URI + const match = uri.match(/^file:\/\/documents\/(.+)$/); + if (!match) { + throw new Error("Invalid URI format"); + } + + const documentName = match[1]; + const content = await loadDocument(documentName); + + return { + contents: [{ + uri, + mimeType: "text/plain", + text: content + }] + }; + } +); + +// List available resources dynamically +server.registerResourceList(async () => { + const documents = await getAvailableDocuments(); + return { + resources: documents.map(doc => ({ + uri: `file://documents/${doc.name}`, + name: doc.name, + mimeType: "text/plain", + description: doc.description + })) + }; +}); +``` + +**When to use Resources vs Tools:** +- **Resources**: For data access with simple URI-based parameters +- **Tools**: For complex operations requiring validation and business logic +- **Resources**: When data is relatively static or template-based +- **Tools**: When operations have side effects or complex workflows + +### Transport Options + +The TypeScript SDK supports two main transport mechanisms: + +#### Streamable HTTP (Recommended for Remote Servers) + +```typescript +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import express from "express"; + +const app = express(); +app.use(express.json()); + +app.post('/mcp', async (req, res) => { + // Create new transport for each request (stateless, prevents request ID collisions) + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined, + enableJsonResponse: true + }); + + res.on('close', () => transport.close()); + + await server.connect(transport); + await transport.handleRequest(req, res, req.body); +}); + +app.listen(3000); +``` + +#### stdio (For Local Integrations) + +```typescript +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; + +const transport = new StdioServerTransport(); +await server.connect(transport); +``` + +**Transport selection:** +- **Streamable HTTP**: Web services, remote access, multiple clients +- **stdio**: Command-line tools, local development, subprocess integration + +### Notification Support + +Notify clients when server state changes: + +```typescript +// Notify when tools list changes +server.notification({ + method: "notifications/tools/list_changed" +}); + +// Notify when resources change +server.notification({ + method: "notifications/resources/list_changed" +}); +``` + +Use notifications sparingly - only when server capabilities genuinely change. + +--- + +## Code Best Practices + +### Code Composability and Reusability + +Your implementation MUST prioritize composability and code reuse: + +1. **Extract Common Functionality**: + - Create reusable helper functions for operations used across multiple tools + - Build shared API clients for HTTP requests instead of duplicating code + - Centralize error handling logic in utility functions + - Extract business logic into dedicated functions that can be composed + - Extract shared markdown or JSON field selection & formatting functionality + +2. **Avoid Duplication**: + - NEVER copy-paste similar code between tools + - If you find yourself writing similar logic twice, extract it into a function + - Common operations like pagination, filtering, field selection, and formatting should be shared + - Authentication/authorization logic should be centralized + +## Building and Running + +Always build your TypeScript code before running: + +```bash +# Build the project +npm run build + +# Run the server +npm start + +# Development with auto-reload +npm run dev +``` + +Always ensure `npm run build` completes successfully before considering the implementation complete. + +## Quality Checklist + +Before finalizing your Node/TypeScript MCP server implementation, ensure: + +### Strategic Design +- [ ] Tools enable complete workflows, not just API endpoint wrappers +- [ ] Tool names reflect natural task subdivisions +- [ ] Response formats optimize for agent context efficiency +- [ ] Human-readable identifiers used where appropriate +- [ ] Error messages guide agents toward correct usage + +### Implementation Quality +- [ ] FOCUSED IMPLEMENTATION: Most important and valuable tools implemented +- [ ] All tools registered using `registerTool` with complete configuration +- [ ] All tools include `title`, `description`, `inputSchema`, and `annotations` +- [ ] Annotations correctly set (readOnlyHint, destructiveHint, idempotentHint, openWorldHint) +- [ ] All tools use Zod schemas for runtime input validation with `.strict()` enforcement +- [ ] All Zod schemas have proper constraints and descriptive error messages +- [ ] All tools have comprehensive descriptions with explicit input/output types +- [ ] Descriptions include return value examples and complete schema documentation +- [ ] Error messages are clear, actionable, and educational + +### TypeScript Quality +- [ ] TypeScript interfaces are defined for all data structures +- [ ] Strict TypeScript is enabled in tsconfig.json +- [ ] No use of `any` type - use `unknown` or proper types instead +- [ ] All async functions have explicit Promise return types +- [ ] Error handling uses proper type guards (e.g., `axios.isAxiosError`, `z.ZodError`) + +### Advanced Features (where applicable) +- [ ] Resources registered for appropriate data endpoints +- [ ] Appropriate transport configured (stdio or streamable HTTP) +- [ ] Notifications implemented for dynamic server capabilities +- [ ] Type-safe with SDK interfaces + +### Project Configuration +- [ ] Package.json includes all necessary dependencies +- [ ] Build script produces working JavaScript in dist/ directory +- [ ] Main entry point is properly configured as dist/index.js +- [ ] Server name follows format: `{service}-mcp-server` +- [ ] tsconfig.json properly configured with strict mode + +### Code Quality +- [ ] Pagination is properly implemented where applicable +- [ ] Large responses check CHARACTER_LIMIT constant and truncate with clear messages +- [ ] Filtering options are provided for potentially large result sets +- [ ] All network operations handle timeouts and connection errors gracefully +- [ ] Common functionality is extracted into reusable functions +- [ ] Return types are consistent across similar operations + +### Testing and Build +- [ ] `npm run build` completes successfully without errors +- [ ] dist/index.js created and executable +- [ ] Server runs: `node dist/index.js --help` +- [ ] All imports resolve correctly +- [ ] Sample tool calls work as expected \ No newline at end of file diff --git a/contributing/samples/skill_script_demo/skills/mcp-builder/references/python_mcp_server.md b/contributing/samples/skill_script_demo/skills/mcp-builder/references/python_mcp_server.md new file mode 100644 index 0000000000..cf7ec996d2 --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/mcp-builder/references/python_mcp_server.md @@ -0,0 +1,719 @@ +# Python MCP Server Implementation Guide + +## Overview + +This document provides Python-specific best practices and examples for implementing MCP servers using the MCP Python SDK. It covers server setup, tool registration patterns, input validation with Pydantic, error handling, and complete working examples. + +--- + +## Quick Reference + +### Key Imports +```python +from mcp.server.fastmcp import FastMCP +from pydantic import BaseModel, Field, field_validator, ConfigDict +from typing import Optional, List, Dict, Any +from enum import Enum +import httpx +``` + +### Server Initialization +```python +mcp = FastMCP("service_mcp") +``` + +### Tool Registration Pattern +```python +@mcp.tool(name="tool_name", annotations={...}) +async def tool_function(params: InputModel) -> str: + # Implementation + pass +``` + +--- + +## MCP Python SDK and FastMCP + +The official MCP Python SDK provides FastMCP, a high-level framework for building MCP servers. It provides: +- Automatic description and inputSchema generation from function signatures and docstrings +- Pydantic model integration for input validation +- Decorator-based tool registration with `@mcp.tool` + +**For complete SDK documentation, use WebFetch to load:** +`https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md` + +## Server Naming Convention + +Python MCP servers must follow this naming pattern: +- **Format**: `{service}_mcp` (lowercase with underscores) +- **Examples**: `github_mcp`, `jira_mcp`, `stripe_mcp` + +The name should be: +- General (not tied to specific features) +- Descriptive of the service/API being integrated +- Easy to infer from the task description +- Without version numbers or dates + +## Tool Implementation + +### Tool Naming + +Use snake_case for tool names (e.g., "search_users", "create_project", "get_channel_info") with clear, action-oriented names. + +**Avoid Naming Conflicts**: Include the service context to prevent overlaps: +- Use "slack_send_message" instead of just "send_message" +- Use "github_create_issue" instead of just "create_issue" +- Use "asana_list_tasks" instead of just "list_tasks" + +### Tool Structure with FastMCP + +Tools are defined using the `@mcp.tool` decorator with Pydantic models for input validation: + +```python +from pydantic import BaseModel, Field, ConfigDict +from mcp.server.fastmcp import FastMCP + +# Initialize the MCP server +mcp = FastMCP("example_mcp") + +# Define Pydantic model for input validation +class ServiceToolInput(BaseModel): + '''Input model for service tool operation.''' + model_config = ConfigDict( + str_strip_whitespace=True, # Auto-strip whitespace from strings + validate_assignment=True, # Validate on assignment + extra='forbid' # Forbid extra fields + ) + + param1: str = Field(..., description="First parameter description (e.g., 'user123', 'project-abc')", min_length=1, max_length=100) + param2: Optional[int] = Field(default=None, description="Optional integer parameter with constraints", ge=0, le=1000) + tags: Optional[List[str]] = Field(default_factory=list, description="List of tags to apply", max_items=10) + +@mcp.tool( + name="service_tool_name", + annotations={ + "title": "Human-Readable Tool Title", + "readOnlyHint": True, # Tool does not modify environment + "destructiveHint": False, # Tool does not perform destructive operations + "idempotentHint": True, # Repeated calls have no additional effect + "openWorldHint": False # Tool does not interact with external entities + } +) +async def service_tool_name(params: ServiceToolInput) -> str: + '''Tool description automatically becomes the 'description' field. + + This tool performs a specific operation on the service. It validates all inputs + using the ServiceToolInput Pydantic model before processing. + + Args: + params (ServiceToolInput): Validated input parameters containing: + - param1 (str): First parameter description + - param2 (Optional[int]): Optional parameter with default + - tags (Optional[List[str]]): List of tags + + Returns: + str: JSON-formatted response containing operation results + ''' + # Implementation here + pass +``` + +## Pydantic v2 Key Features + +- Use `model_config` instead of nested `Config` class +- Use `field_validator` instead of deprecated `validator` +- Use `model_dump()` instead of deprecated `dict()` +- Validators require `@classmethod` decorator +- Type hints are required for validator methods + +```python +from pydantic import BaseModel, Field, field_validator, ConfigDict + +class CreateUserInput(BaseModel): + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True + ) + + name: str = Field(..., description="User's full name", min_length=1, max_length=100) + email: str = Field(..., description="User's email address", pattern=r'^[\w\.-]+@[\w\.-]+\.\w+$') + age: int = Field(..., description="User's age", ge=0, le=150) + + @field_validator('email') + @classmethod + def validate_email(cls, v: str) -> str: + if not v.strip(): + raise ValueError("Email cannot be empty") + return v.lower() +``` + +## Response Format Options + +Support multiple output formats for flexibility: + +```python +from enum import Enum + +class ResponseFormat(str, Enum): + '''Output format for tool responses.''' + MARKDOWN = "markdown" + JSON = "json" + +class UserSearchInput(BaseModel): + query: str = Field(..., description="Search query") + response_format: ResponseFormat = Field( + default=ResponseFormat.MARKDOWN, + description="Output format: 'markdown' for human-readable or 'json' for machine-readable" + ) +``` + +**Markdown format**: +- Use headers, lists, and formatting for clarity +- Convert timestamps to human-readable format (e.g., "2024-01-15 10:30:00 UTC" instead of epoch) +- Show display names with IDs in parentheses (e.g., "@john.doe (U123456)") +- Omit verbose metadata (e.g., show only one profile image URL, not all sizes) +- Group related information logically + +**JSON format**: +- Return complete, structured data suitable for programmatic processing +- Include all available fields and metadata +- Use consistent field names and types + +## Pagination Implementation + +For tools that list resources: + +```python +class ListInput(BaseModel): + limit: Optional[int] = Field(default=20, description="Maximum results to return", ge=1, le=100) + offset: Optional[int] = Field(default=0, description="Number of results to skip for pagination", ge=0) + +async def list_items(params: ListInput) -> str: + # Make API request with pagination + data = await api_request(limit=params.limit, offset=params.offset) + + # Return pagination info + response = { + "total": data["total"], + "count": len(data["items"]), + "offset": params.offset, + "items": data["items"], + "has_more": data["total"] > params.offset + len(data["items"]), + "next_offset": params.offset + len(data["items"]) if data["total"] > params.offset + len(data["items"]) else None + } + return json.dumps(response, indent=2) +``` + +## Error Handling + +Provide clear, actionable error messages: + +```python +def _handle_api_error(e: Exception) -> str: + '''Consistent error formatting across all tools.''' + if isinstance(e, httpx.HTTPStatusError): + if e.response.status_code == 404: + return "Error: Resource not found. Please check the ID is correct." + elif e.response.status_code == 403: + return "Error: Permission denied. You don't have access to this resource." + elif e.response.status_code == 429: + return "Error: Rate limit exceeded. Please wait before making more requests." + return f"Error: API request failed with status {e.response.status_code}" + elif isinstance(e, httpx.TimeoutException): + return "Error: Request timed out. Please try again." + return f"Error: Unexpected error occurred: {type(e).__name__}" +``` + +## Shared Utilities + +Extract common functionality into reusable functions: + +```python +# Shared API request function +async def _make_api_request(endpoint: str, method: str = "GET", **kwargs) -> dict: + '''Reusable function for all API calls.''' + async with httpx.AsyncClient() as client: + response = await client.request( + method, + f"{API_BASE_URL}/{endpoint}", + timeout=30.0, + **kwargs + ) + response.raise_for_status() + return response.json() +``` + +## Async/Await Best Practices + +Always use async/await for network requests and I/O operations: + +```python +# Good: Async network request +async def fetch_data(resource_id: str) -> dict: + async with httpx.AsyncClient() as client: + response = await client.get(f"{API_URL}/resource/{resource_id}") + response.raise_for_status() + return response.json() + +# Bad: Synchronous request +def fetch_data(resource_id: str) -> dict: + response = requests.get(f"{API_URL}/resource/{resource_id}") # Blocks + return response.json() +``` + +## Type Hints + +Use type hints throughout: + +```python +from typing import Optional, List, Dict, Any + +async def get_user(user_id: str) -> Dict[str, Any]: + data = await fetch_user(user_id) + return {"id": data["id"], "name": data["name"]} +``` + +## Tool Docstrings + +Every tool must have comprehensive docstrings with explicit type information: + +```python +async def search_users(params: UserSearchInput) -> str: + ''' + Search for users in the Example system by name, email, or team. + + This tool searches across all user profiles in the Example platform, + supporting partial matches and various search filters. It does NOT + create or modify users, only searches existing ones. + + Args: + params (UserSearchInput): Validated input parameters containing: + - query (str): Search string to match against names/emails (e.g., "john", "@example.com", "team:marketing") + - limit (Optional[int]): Maximum results to return, between 1-100 (default: 20) + - offset (Optional[int]): Number of results to skip for pagination (default: 0) + + Returns: + str: JSON-formatted string containing search results with the following schema: + + Success response: + { + "total": int, # Total number of matches found + "count": int, # Number of results in this response + "offset": int, # Current pagination offset + "users": [ + { + "id": str, # User ID (e.g., "U123456789") + "name": str, # Full name (e.g., "John Doe") + "email": str, # Email address (e.g., "john@example.com") + "team": str # Team name (e.g., "Marketing") - optional + } + ] + } + + Error response: + "Error: " or "No users found matching ''" + + Examples: + - Use when: "Find all marketing team members" -> params with query="team:marketing" + - Use when: "Search for John's account" -> params with query="john" + - Don't use when: You need to create a user (use example_create_user instead) + - Don't use when: You have a user ID and need full details (use example_get_user instead) + + Error Handling: + - Input validation errors are handled by Pydantic model + - Returns "Error: Rate limit exceeded" if too many requests (429 status) + - Returns "Error: Invalid API authentication" if API key is invalid (401 status) + - Returns formatted list of results or "No users found matching 'query'" + ''' +``` + +## Complete Example + +See below for a complete Python MCP server example: + +```python +#!/usr/bin/env python3 +''' +MCP Server for Example Service. + +This server provides tools to interact with Example API, including user search, +project management, and data export capabilities. +''' + +from typing import Optional, List, Dict, Any +from enum import Enum +import httpx +from pydantic import BaseModel, Field, field_validator, ConfigDict +from mcp.server.fastmcp import FastMCP + +# Initialize the MCP server +mcp = FastMCP("example_mcp") + +# Constants +API_BASE_URL = "https://api.example.com/v1" + +# Enums +class ResponseFormat(str, Enum): + '''Output format for tool responses.''' + MARKDOWN = "markdown" + JSON = "json" + +# Pydantic Models for Input Validation +class UserSearchInput(BaseModel): + '''Input model for user search operations.''' + model_config = ConfigDict( + str_strip_whitespace=True, + validate_assignment=True + ) + + query: str = Field(..., description="Search string to match against names/emails", min_length=2, max_length=200) + limit: Optional[int] = Field(default=20, description="Maximum results to return", ge=1, le=100) + offset: Optional[int] = Field(default=0, description="Number of results to skip for pagination", ge=0) + response_format: ResponseFormat = Field(default=ResponseFormat.MARKDOWN, description="Output format") + + @field_validator('query') + @classmethod + def validate_query(cls, v: str) -> str: + if not v.strip(): + raise ValueError("Query cannot be empty or whitespace only") + return v.strip() + +# Shared utility functions +async def _make_api_request(endpoint: str, method: str = "GET", **kwargs) -> dict: + '''Reusable function for all API calls.''' + async with httpx.AsyncClient() as client: + response = await client.request( + method, + f"{API_BASE_URL}/{endpoint}", + timeout=30.0, + **kwargs + ) + response.raise_for_status() + return response.json() + +def _handle_api_error(e: Exception) -> str: + '''Consistent error formatting across all tools.''' + if isinstance(e, httpx.HTTPStatusError): + if e.response.status_code == 404: + return "Error: Resource not found. Please check the ID is correct." + elif e.response.status_code == 403: + return "Error: Permission denied. You don't have access to this resource." + elif e.response.status_code == 429: + return "Error: Rate limit exceeded. Please wait before making more requests." + return f"Error: API request failed with status {e.response.status_code}" + elif isinstance(e, httpx.TimeoutException): + return "Error: Request timed out. Please try again." + return f"Error: Unexpected error occurred: {type(e).__name__}" + +# Tool definitions +@mcp.tool( + name="example_search_users", + annotations={ + "title": "Search Example Users", + "readOnlyHint": True, + "destructiveHint": False, + "idempotentHint": True, + "openWorldHint": True + } +) +async def example_search_users(params: UserSearchInput) -> str: + '''Search for users in the Example system by name, email, or team. + + [Full docstring as shown above] + ''' + try: + # Make API request using validated parameters + data = await _make_api_request( + "users/search", + params={ + "q": params.query, + "limit": params.limit, + "offset": params.offset + } + ) + + users = data.get("users", []) + total = data.get("total", 0) + + if not users: + return f"No users found matching '{params.query}'" + + # Format response based on requested format + if params.response_format == ResponseFormat.MARKDOWN: + lines = [f"# User Search Results: '{params.query}'", ""] + lines.append(f"Found {total} users (showing {len(users)})") + lines.append("") + + for user in users: + lines.append(f"## {user['name']} ({user['id']})") + lines.append(f"- **Email**: {user['email']}") + if user.get('team'): + lines.append(f"- **Team**: {user['team']}") + lines.append("") + + return "\n".join(lines) + + else: + # Machine-readable JSON format + import json + response = { + "total": total, + "count": len(users), + "offset": params.offset, + "users": users + } + return json.dumps(response, indent=2) + + except Exception as e: + return _handle_api_error(e) + +if __name__ == "__main__": + mcp.run() +``` + +--- + +## Advanced FastMCP Features + +### Context Parameter Injection + +FastMCP can automatically inject a `Context` parameter into tools for advanced capabilities like logging, progress reporting, resource reading, and user interaction: + +```python +from mcp.server.fastmcp import FastMCP, Context + +mcp = FastMCP("example_mcp") + +@mcp.tool() +async def advanced_search(query: str, ctx: Context) -> str: + '''Advanced tool with context access for logging and progress.''' + + # Report progress for long operations + await ctx.report_progress(0.25, "Starting search...") + + # Log information for debugging + await ctx.log_info("Processing query", {"query": query, "timestamp": datetime.now()}) + + # Perform search + results = await search_api(query) + await ctx.report_progress(0.75, "Formatting results...") + + # Access server configuration + server_name = ctx.fastmcp.name + + return format_results(results) + +@mcp.tool() +async def interactive_tool(resource_id: str, ctx: Context) -> str: + '''Tool that can request additional input from users.''' + + # Request sensitive information when needed + api_key = await ctx.elicit( + prompt="Please provide your API key:", + input_type="password" + ) + + # Use the provided key + return await api_call(resource_id, api_key) +``` + +**Context capabilities:** +- `ctx.report_progress(progress, message)` - Report progress for long operations +- `ctx.log_info(message, data)` / `ctx.log_error()` / `ctx.log_debug()` - Logging +- `ctx.elicit(prompt, input_type)` - Request input from users +- `ctx.fastmcp.name` - Access server configuration +- `ctx.read_resource(uri)` - Read MCP resources + +### Resource Registration + +Expose data as resources for efficient, template-based access: + +```python +@mcp.resource("file://documents/{name}") +async def get_document(name: str) -> str: + '''Expose documents as MCP resources. + + Resources are useful for static or semi-static data that doesn't + require complex parameters. They use URI templates for flexible access. + ''' + document_path = f"./docs/{name}" + with open(document_path, "r") as f: + return f.read() + +@mcp.resource("config://settings/{key}") +async def get_setting(key: str, ctx: Context) -> str: + '''Expose configuration as resources with context.''' + settings = await load_settings() + return json.dumps(settings.get(key, {})) +``` + +**When to use Resources vs Tools:** +- **Resources**: For data access with simple parameters (URI templates) +- **Tools**: For complex operations with validation and business logic + +### Structured Output Types + +FastMCP supports multiple return types beyond strings: + +```python +from typing import TypedDict +from dataclasses import dataclass +from pydantic import BaseModel + +# TypedDict for structured returns +class UserData(TypedDict): + id: str + name: str + email: str + +@mcp.tool() +async def get_user_typed(user_id: str) -> UserData: + '''Returns structured data - FastMCP handles serialization.''' + return {"id": user_id, "name": "John Doe", "email": "john@example.com"} + +# Pydantic models for complex validation +class DetailedUser(BaseModel): + id: str + name: str + email: str + created_at: datetime + metadata: Dict[str, Any] + +@mcp.tool() +async def get_user_detailed(user_id: str) -> DetailedUser: + '''Returns Pydantic model - automatically generates schema.''' + user = await fetch_user(user_id) + return DetailedUser(**user) +``` + +### Lifespan Management + +Initialize resources that persist across requests: + +```python +from contextlib import asynccontextmanager + +@asynccontextmanager +async def app_lifespan(): + '''Manage resources that live for the server's lifetime.''' + # Initialize connections, load config, etc. + db = await connect_to_database() + config = load_configuration() + + # Make available to all tools + yield {"db": db, "config": config} + + # Cleanup on shutdown + await db.close() + +mcp = FastMCP("example_mcp", lifespan=app_lifespan) + +@mcp.tool() +async def query_data(query: str, ctx: Context) -> str: + '''Access lifespan resources through context.''' + db = ctx.request_context.lifespan_state["db"] + results = await db.query(query) + return format_results(results) +``` + +### Transport Options + +FastMCP supports two main transport mechanisms: + +```python +# stdio transport (for local tools) - default +if __name__ == "__main__": + mcp.run() + +# Streamable HTTP transport (for remote servers) +if __name__ == "__main__": + mcp.run(transport="streamable_http", port=8000) +``` + +**Transport selection:** +- **stdio**: Command-line tools, local integrations, subprocess execution +- **Streamable HTTP**: Web services, remote access, multiple clients + +--- + +## Code Best Practices + +### Code Composability and Reusability + +Your implementation MUST prioritize composability and code reuse: + +1. **Extract Common Functionality**: + - Create reusable helper functions for operations used across multiple tools + - Build shared API clients for HTTP requests instead of duplicating code + - Centralize error handling logic in utility functions + - Extract business logic into dedicated functions that can be composed + - Extract shared markdown or JSON field selection & formatting functionality + +2. **Avoid Duplication**: + - NEVER copy-paste similar code between tools + - If you find yourself writing similar logic twice, extract it into a function + - Common operations like pagination, filtering, field selection, and formatting should be shared + - Authentication/authorization logic should be centralized + +### Python-Specific Best Practices + +1. **Use Type Hints**: Always include type annotations for function parameters and return values +2. **Pydantic Models**: Define clear Pydantic models for all input validation +3. **Avoid Manual Validation**: Let Pydantic handle input validation with constraints +4. **Proper Imports**: Group imports (standard library, third-party, local) +5. **Error Handling**: Use specific exception types (httpx.HTTPStatusError, not generic Exception) +6. **Async Context Managers**: Use `async with` for resources that need cleanup +7. **Constants**: Define module-level constants in UPPER_CASE + +## Quality Checklist + +Before finalizing your Python MCP server implementation, ensure: + +### Strategic Design +- [ ] Tools enable complete workflows, not just API endpoint wrappers +- [ ] Tool names reflect natural task subdivisions +- [ ] Response formats optimize for agent context efficiency +- [ ] Human-readable identifiers used where appropriate +- [ ] Error messages guide agents toward correct usage + +### Implementation Quality +- [ ] FOCUSED IMPLEMENTATION: Most important and valuable tools implemented +- [ ] All tools have descriptive names and documentation +- [ ] Return types are consistent across similar operations +- [ ] Error handling is implemented for all external calls +- [ ] Server name follows format: `{service}_mcp` +- [ ] All network operations use async/await +- [ ] Common functionality is extracted into reusable functions +- [ ] Error messages are clear, actionable, and educational +- [ ] Outputs are properly validated and formatted + +### Tool Configuration +- [ ] All tools implement 'name' and 'annotations' in the decorator +- [ ] Annotations correctly set (readOnlyHint, destructiveHint, idempotentHint, openWorldHint) +- [ ] All tools use Pydantic BaseModel for input validation with Field() definitions +- [ ] All Pydantic Fields have explicit types and descriptions with constraints +- [ ] All tools have comprehensive docstrings with explicit input/output types +- [ ] Docstrings include complete schema structure for dict/JSON returns +- [ ] Pydantic models handle input validation (no manual validation needed) + +### Advanced Features (where applicable) +- [ ] Context injection used for logging, progress, or elicitation +- [ ] Resources registered for appropriate data endpoints +- [ ] Lifespan management implemented for persistent connections +- [ ] Structured output types used (TypedDict, Pydantic models) +- [ ] Appropriate transport configured (stdio or streamable HTTP) + +### Code Quality +- [ ] File includes proper imports including Pydantic imports +- [ ] Pagination is properly implemented where applicable +- [ ] Filtering options are provided for potentially large result sets +- [ ] All async functions are properly defined with `async def` +- [ ] HTTP client usage follows async patterns with proper context managers +- [ ] Type hints are used throughout the code +- [ ] Constants are defined at module level in UPPER_CASE + +### Testing +- [ ] Server runs successfully: `python your_server.py --help` +- [ ] All imports resolve correctly +- [ ] Sample tool calls work as expected +- [ ] Error scenarios handled gracefully \ No newline at end of file diff --git a/contributing/samples/skill_script_demo/skills/mcp-builder/scripts/connections.py b/contributing/samples/skill_script_demo/skills/mcp-builder/scripts/connections.py new file mode 100644 index 0000000000..b828211677 --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/mcp-builder/scripts/connections.py @@ -0,0 +1,160 @@ +"""Lightweight connection handling for MCP servers.""" + +from abc import ABC +from abc import abstractmethod +from contextlib import AsyncExitStack +from typing import Any + +from mcp import ClientSession +from mcp import StdioServerParameters +from mcp.client.sse import sse_client +from mcp.client.stdio import stdio_client +from mcp.client.streamable_http import streamablehttp_client + + +class MCPConnection(ABC): + """Base class for MCP server connections.""" + + def __init__(self): + self.session = None + self._stack = None + + @abstractmethod + def _create_context(self): + """Create the connection context based on connection type.""" + + async def __aenter__(self): + """Initialize MCP server connection.""" + self._stack = AsyncExitStack() + await self._stack.__aenter__() + + try: + ctx = self._create_context() + result = await self._stack.enter_async_context(ctx) + + if len(result) == 2: + read, write = result + elif len(result) == 3: + read, write, _ = result + else: + raise ValueError(f"Unexpected context result: {result}") + + session_ctx = ClientSession(read, write) + self.session = await self._stack.enter_async_context(session_ctx) + await self.session.initialize() + return self + except BaseException: + await self._stack.__aexit__(None, None, None) + raise + + async def __aexit__(self, exc_type, exc_val, exc_tb): + """Clean up MCP server connection resources.""" + if self._stack: + await self._stack.__aexit__(exc_type, exc_val, exc_tb) + self.session = None + self._stack = None + + async def list_tools(self) -> list[dict[str, Any]]: + """Retrieve available tools from the MCP server.""" + response = await self.session.list_tools() + return [ + { + "name": tool.name, + "description": tool.description, + "input_schema": tool.inputSchema, + } + for tool in response.tools + ] + + async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -> Any: + """Call a tool on the MCP server with provided arguments.""" + result = await self.session.call_tool(tool_name, arguments=arguments) + return result.content + + +class MCPConnectionStdio(MCPConnection): + """MCP connection using standard input/output.""" + + def __init__( + self, command: str, args: list[str] = None, env: dict[str, str] = None + ): + super().__init__() + self.command = command + self.args = args or [] + self.env = env + + def _create_context(self): + return stdio_client( + StdioServerParameters( + command=self.command, args=self.args, env=self.env + ) + ) + + +class MCPConnectionSSE(MCPConnection): + """MCP connection using Server-Sent Events.""" + + def __init__(self, url: str, headers: dict[str, str] = None): + super().__init__() + self.url = url + self.headers = headers or {} + + def _create_context(self): + return sse_client(url=self.url, headers=self.headers) + + +class MCPConnectionHTTP(MCPConnection): + """MCP connection using Streamable HTTP.""" + + def __init__(self, url: str, headers: dict[str, str] = None): + super().__init__() + self.url = url + self.headers = headers or {} + + def _create_context(self): + return streamablehttp_client(url=self.url, headers=self.headers) + + +def create_connection( + transport: str, + command: str = None, + args: list[str] = None, + env: dict[str, str] = None, + url: str = None, + headers: dict[str, str] = None, +) -> MCPConnection: + """Factory function to create the appropriate MCP connection. + + Args: + transport: Connection type ("stdio", "sse", or "http") + command: Command to run (stdio only) + args: Command arguments (stdio only) + env: Environment variables (stdio only) + url: Server URL (sse and http only) + headers: HTTP headers (sse and http only) + + Returns: + MCPConnection instance + """ + transport = transport.lower() + + if transport == "stdio": + if not command: + raise ValueError("Command is required for stdio transport") + return MCPConnectionStdio(command=command, args=args, env=env) + + elif transport == "sse": + if not url: + raise ValueError("URL is required for sse transport") + return MCPConnectionSSE(url=url, headers=headers) + + elif transport in ["http", "streamable_http", "streamable-http"]: + if not url: + raise ValueError("URL is required for http transport") + return MCPConnectionHTTP(url=url, headers=headers) + + else: + raise ValueError( + f"Unsupported transport type: {transport}. Use 'stdio', 'sse', or" + " 'http'" + ) diff --git a/contributing/samples/skill_script_demo/skills/mcp-builder/scripts/evaluation.py b/contributing/samples/skill_script_demo/skills/mcp-builder/scripts/evaluation.py new file mode 100644 index 0000000000..fd5542f169 --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/mcp-builder/scripts/evaluation.py @@ -0,0 +1,428 @@ +"""MCP Server Evaluation Harness + +This script evaluates MCP servers by running test questions against them using Claude. +""" + +import argparse +import asyncio +import json +from pathlib import Path +import re +import sys +import time +import traceback +from typing import Any +import xml.etree.ElementTree as ET + +from anthropic import Anthropic +from connections import create_connection + +EVALUATION_PROMPT = """You are an AI assistant with access to tools. + +When given a task, you MUST: +1. Use the available tools to complete the task +2. Provide summary of each step in your approach, wrapped in tags +3. Provide feedback on the tools provided, wrapped in tags +4. Provide your final response, wrapped in tags + +Summary Requirements: +- In your tags, you must explain: + - The steps you took to complete the task + - Which tools you used, in what order, and why + - The inputs you provided to each tool + - The outputs you received from each tool + - A summary for how you arrived at the response + +Feedback Requirements: +- In your tags, provide constructive feedback on the tools: + - Comment on tool names: Are they clear and descriptive? + - Comment on input parameters: Are they well-documented? Are required vs optional parameters clear? + - Comment on descriptions: Do they accurately describe what the tool does? + - Comment on any errors encountered during tool usage: Did the tool fail to execute? Did the tool return too many tokens? + - Identify specific areas for improvement and explain WHY they would help + - Be specific and actionable in your suggestions + +Response Requirements: +- Your response should be concise and directly address what was asked +- Always wrap your final response in tags +- If you cannot solve the task return NOT_FOUND +- For numeric responses, provide just the number +- For IDs, provide just the ID +- For names or text, provide the exact text requested +- Your response should go last""" + + +def parse_evaluation_file(file_path: Path) -> list[dict[str, Any]]: + """Parse XML evaluation file with qa_pair elements.""" + try: + tree = ET.parse(file_path) + root = tree.getroot() + evaluations = [] + + for qa_pair in root.findall(".//qa_pair"): + question_elem = qa_pair.find("question") + answer_elem = qa_pair.find("answer") + + if question_elem is not None and answer_elem is not None: + evaluations.append({ + "question": (question_elem.text or "").strip(), + "answer": (answer_elem.text or "").strip(), + }) + + return evaluations + except Exception as e: + print(f"Error parsing evaluation file {file_path}: {e}") + return [] + + +def extract_xml_content(text: str, tag: str) -> str | None: + """Extract content from XML tags.""" + pattern = rf"<{tag}>(.*?)" + matches = re.findall(pattern, text, re.DOTALL) + return matches[-1].strip() if matches else None + + +async def agent_loop( + client: Anthropic, + model: str, + question: str, + tools: list[dict[str, Any]], + connection: Any, +) -> tuple[str, dict[str, Any]]: + """Run the agent loop with MCP tools.""" + messages = [{"role": "user", "content": question}] + + response = await asyncio.to_thread( + client.messages.create, + model=model, + max_tokens=4096, + system=EVALUATION_PROMPT, + messages=messages, + tools=tools, + ) + + messages.append({"role": "assistant", "content": response.content}) + + tool_metrics = {} + + while response.stop_reason == "tool_use": + tool_use = next( + block for block in response.content if block.type == "tool_use" + ) + tool_name = tool_use.name + tool_input = tool_use.input + + tool_start_ts = time.time() + try: + tool_result = await connection.call_tool(tool_name, tool_input) + tool_response = ( + json.dumps(tool_result) + if isinstance(tool_result, (dict, list)) + else str(tool_result) + ) + except Exception as e: + tool_response = f"Error executing tool {tool_name}: {str(e)}\n" + tool_response += traceback.format_exc() + tool_duration = time.time() - tool_start_ts + + if tool_name not in tool_metrics: + tool_metrics[tool_name] = {"count": 0, "durations": []} + tool_metrics[tool_name]["count"] += 1 + tool_metrics[tool_name]["durations"].append(tool_duration) + + messages.append({ + "role": "user", + "content": [{ + "type": "tool_result", + "tool_use_id": tool_use.id, + "content": tool_response, + }], + }) + + response = await asyncio.to_thread( + client.messages.create, + model=model, + max_tokens=4096, + system=EVALUATION_PROMPT, + messages=messages, + tools=tools, + ) + messages.append({"role": "assistant", "content": response.content}) + + response_text = next( + (block.text for block in response.content if hasattr(block, "text")), + None, + ) + return response_text, tool_metrics + + +async def evaluate_single_task( + client: Anthropic, + model: str, + qa_pair: dict[str, Any], + tools: list[dict[str, Any]], + connection: Any, + task_index: int, +) -> dict[str, Any]: + """Evaluate a single QA pair with the given tools.""" + start_time = time.time() + + print( + f"Task {task_index + 1}: Running task with question:" + f" {qa_pair['question']}" + ) + response, tool_metrics = await agent_loop( + client, model, qa_pair["question"], tools, connection + ) + + response_value = extract_xml_content(response, "response") + summary = extract_xml_content(response, "summary") + feedback = extract_xml_content(response, "feedback") + + duration_seconds = time.time() - start_time + + return { + "question": qa_pair["question"], + "expected": qa_pair["answer"], + "actual": response_value, + "score": ( + int(response_value == qa_pair["answer"]) if response_value else 0 + ), + "total_duration": duration_seconds, + "tool_calls": tool_metrics, + "num_tool_calls": sum( + len(metrics["durations"]) for metrics in tool_metrics.values() + ), + "summary": summary, + "feedback": feedback, + } + + +REPORT_HEADER = """ +# Evaluation Report + +## Summary + +- **Accuracy**: {correct}/{total} ({accuracy:.1f}%) +- **Average Task Duration**: {average_duration_s:.2f}s +- **Average Tool Calls per Task**: {average_tool_calls:.2f} +- **Total Tool Calls**: {total_tool_calls} + +--- +""" + +TASK_TEMPLATE = """ +### Task {task_num} + +**Question**: {question} +**Ground Truth Answer**: `{expected_answer}` +**Actual Answer**: `{actual_answer}` +**Correct**: {correct_indicator} +**Duration**: {total_duration:.2f}s +**Tool Calls**: {tool_calls} + +**Summary** +{summary} + +**Feedback** +{feedback} + +--- +""" + + +async def run_evaluation( + eval_path: Path, + connection: Any, + model: str = "claude-3-7-sonnet-20250219", +) -> str: + """Run evaluation with MCP server tools.""" + print("🚀 Starting Evaluation") + + client = Anthropic() + + tools = await connection.list_tools() + print(f"📋 Loaded {len(tools)} tools from MCP server") + + qa_pairs = parse_evaluation_file(eval_path) + print(f"📋 Loaded {len(qa_pairs)} evaluation tasks") + + results = [] + for i, qa_pair in enumerate(qa_pairs): + print(f"Processing task {i + 1}/{len(qa_pairs)}") + result = await evaluate_single_task( + client, model, qa_pair, tools, connection, i + ) + results.append(result) + + correct = sum(r["score"] for r in results) + accuracy = (correct / len(results)) * 100 if results else 0 + average_duration_s = ( + sum(r["total_duration"] for r in results) / len(results) if results else 0 + ) + average_tool_calls = ( + sum(r["num_tool_calls"] for r in results) / len(results) if results else 0 + ) + total_tool_calls = sum(r["num_tool_calls"] for r in results) + + report = REPORT_HEADER.format( + correct=correct, + total=len(results), + accuracy=accuracy, + average_duration_s=average_duration_s, + average_tool_calls=average_tool_calls, + total_tool_calls=total_tool_calls, + ) + + report += "".join([ + TASK_TEMPLATE.format( + task_num=i + 1, + question=qa_pair["question"], + expected_answer=qa_pair["answer"], + actual_answer=result["actual"] or "N/A", + correct_indicator="✅" if result["score"] else "❌", + total_duration=result["total_duration"], + tool_calls=json.dumps(result["tool_calls"], indent=2), + summary=result["summary"] or "N/A", + feedback=result["feedback"] or "N/A", + ) + for i, (qa_pair, result) in enumerate(zip(qa_pairs, results)) + ]) + + return report + + +def parse_headers(header_list: list[str]) -> dict[str, str]: + """Parse header strings in format 'Key: Value' into a dictionary.""" + headers = {} + if not header_list: + return headers + + for header in header_list: + if ":" in header: + key, value = header.split(":", 1) + headers[key.strip()] = value.strip() + else: + print(f"Warning: Ignoring malformed header: {header}") + return headers + + +def parse_env_vars(env_list: list[str]) -> dict[str, str]: + """Parse environment variable strings in format 'KEY=VALUE' into a dictionary.""" + env = {} + if not env_list: + return env + + for env_var in env_list: + if "=" in env_var: + key, value = env_var.split("=", 1) + env[key.strip()] = value.strip() + else: + print(f"Warning: Ignoring malformed environment variable: {env_var}") + return env + + +async def main(): + parser = argparse.ArgumentParser( + description="Evaluate MCP servers using test questions", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + # Evaluate a local stdio MCP server + python evaluation.py -t stdio -c python -a my_server.py eval.xml + + # Evaluate an SSE MCP server + python evaluation.py -t sse -u https://example.com/mcp -H "Authorization: Bearer token" eval.xml + + # Evaluate an HTTP MCP server with custom model + python evaluation.py -t http -u https://example.com/mcp -m claude-3-5-sonnet-20241022 eval.xml + """, + ) + + parser.add_argument( + "eval_file", type=Path, help="Path to evaluation XML file" + ) + parser.add_argument( + "-t", + "--transport", + choices=["stdio", "sse", "http"], + default="stdio", + help="Transport type (default: stdio)", + ) + parser.add_argument( + "-m", + "--model", + default="claude-3-7-sonnet-20250219", + help="Claude model to use (default: claude-3-7-sonnet-20250219)", + ) + + stdio_group = parser.add_argument_group("stdio options") + stdio_group.add_argument( + "-c", "--command", help="Command to run MCP server (stdio only)" + ) + stdio_group.add_argument( + "-a", "--args", nargs="+", help="Arguments for the command (stdio only)" + ) + stdio_group.add_argument( + "-e", + "--env", + nargs="+", + help="Environment variables in KEY=VALUE format (stdio only)", + ) + + remote_group = parser.add_argument_group("sse/http options") + remote_group.add_argument( + "-u", "--url", help="MCP server URL (sse/http only)" + ) + remote_group.add_argument( + "-H", + "--header", + nargs="+", + dest="headers", + help="HTTP headers in 'Key: Value' format (sse/http only)", + ) + + parser.add_argument( + "-o", + "--output", + type=Path, + help="Output file for evaluation report (default: stdout)", + ) + + args = parser.parse_args() + + if not args.eval_file.exists(): + print(f"Error: Evaluation file not found: {args.eval_file}") + sys.exit(1) + + headers = parse_headers(args.headers) if args.headers else None + env_vars = parse_env_vars(args.env) if args.env else None + + try: + connection = create_connection( + transport=args.transport, + command=args.command, + args=args.args, + env=env_vars, + url=args.url, + headers=headers, + ) + except ValueError as e: + print(f"Error: {e}") + sys.exit(1) + + print(f"🔗 Connecting to MCP server via {args.transport}...") + + async with connection: + print("✅ Connected successfully") + report = await run_evaluation(args.eval_file, connection, args.model) + + if args.output: + args.output.write_text(report) + print(f"\n✅ Report saved to {args.output}") + else: + print("\n" + report) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/contributing/samples/skill_script_demo/skills/mcp-builder/scripts/example_evaluation.xml b/contributing/samples/skill_script_demo/skills/mcp-builder/scripts/example_evaluation.xml new file mode 100644 index 0000000000..41e4459b5a --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/mcp-builder/scripts/example_evaluation.xml @@ -0,0 +1,22 @@ + + + Calculate the compound interest on $10,000 invested at 5% annual interest rate, compounded monthly for 3 years. What is the final amount in dollars (rounded to 2 decimal places)? + 11614.72 + + + A projectile is launched at a 45-degree angle with an initial velocity of 50 m/s. Calculate the total distance (in meters) it has traveled from the launch point after 2 seconds, assuming g=9.8 m/s². Round to 2 decimal places. + 87.25 + + + A sphere has a volume of 500 cubic meters. Calculate its surface area in square meters. Round to 2 decimal places. + 304.65 + + + Calculate the population standard deviation of this dataset: [12, 15, 18, 22, 25, 30, 35]. Round to 2 decimal places. + 7.61 + + + Calculate the pH of a solution with a hydrogen ion concentration of 3.5 × 10^-5 M. Round to 2 decimal places. + 4.46 + + diff --git a/contributing/samples/skill_script_demo/skills/mcp-builder/scripts/requirements.txt b/contributing/samples/skill_script_demo/skills/mcp-builder/scripts/requirements.txt new file mode 100644 index 0000000000..e73e5d1e35 --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/mcp-builder/scripts/requirements.txt @@ -0,0 +1,2 @@ +anthropic>=0.39.0 +mcp>=1.1.0 diff --git a/contributing/samples/skill_script_demo/skills/python-helper/SKILL.md b/contributing/samples/skill_script_demo/skills/python-helper/SKILL.md new file mode 100644 index 0000000000..249e76b325 --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/python-helper/SKILL.md @@ -0,0 +1,33 @@ +--- +name: python-helper +description: Python utility scripts for code analysis, data processing, and generation tasks. +version: 1.0.0 +--- + +# Python Helper Skill + +A collection of lightweight Python utility scripts for common development tasks. + +## Available Scripts + +### `fibonacci.py` +Generates a Fibonacci sequence. Pass the desired count as an argument. + +**Usage**: `execute_skill_script(skill_name="python-helper", script_name="fibonacci.py", input_args="10")` + +### `word_count.py` +Analyzes text and reports word frequency statistics. Pass the text to analyze as an argument. + +**Usage**: `execute_skill_script(skill_name="python-helper", script_name="word_count.py", input_args="the quick brown fox jumps over the lazy dog the fox")` + +### `json_format.py` +Pretty-prints and validates a JSON string. Pass the JSON as a single quoted argument. + +**Usage**: `execute_skill_script(skill_name="python-helper", script_name="json_format.py", input_args='{"name":"Alice","scores":[90,85,92]}')` + +## Workflow + +1. Use `load_skill` to read these instructions. +2. Use `load_skill_resource` to inspect a script's source if needed. +3. Use `execute_skill_script` with appropriate `input_args` to run a script. +4. Interpret the script's stdout and present results to the user. diff --git a/contributing/samples/skill_script_demo/skills/python-helper/references/usage.md b/contributing/samples/skill_script_demo/skills/python-helper/references/usage.md new file mode 100644 index 0000000000..a5d425cccd --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/python-helper/references/usage.md @@ -0,0 +1,17 @@ +# Python Helper Usage Guide + +## Quick Reference + +| Script | Purpose | Example Args | +|--------|---------|-------------| +| `fibonacci.py` | Generate Fibonacci sequence | `"15"` (count) | +| `word_count.py` | Word frequency analysis | `"hello world hello"` | +| `json_format.py` | Validate & pretty-print JSON | `'{"key":"value"}'` | + +## Tips + +- All scripts write results to **stdout**. +- Pass arguments via the `input_args` parameter as a space-separated string. +- `fibonacci.py` defaults to 10 numbers if no argument is given. +- `word_count.py` treats all arguments as the text to analyze. +- `json_format.py` joins all arguments as a single JSON string. diff --git a/contributing/samples/skill_script_demo/skills/python-helper/scripts/fibonacci.py b/contributing/samples/skill_script_demo/skills/python-helper/scripts/fibonacci.py new file mode 100644 index 0000000000..fb0ffd3679 --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/python-helper/scripts/fibonacci.py @@ -0,0 +1,12 @@ +"""Generate a Fibonacci sequence of N numbers.""" + +import sys + +n = int(sys.argv[1]) if len(sys.argv) > 1 else 10 +a, b = 0, 1 +result = [] +for _ in range(n): + result.append(a) + a, b = b, a + b +print(f"Fibonacci({n}): {result}") +print(f"Sum: {sum(result)}") diff --git a/contributing/samples/skill_script_demo/skills/python-helper/scripts/json_format.py b/contributing/samples/skill_script_demo/skills/python-helper/scripts/json_format.py new file mode 100644 index 0000000000..819fa4da67 --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/python-helper/scripts/json_format.py @@ -0,0 +1,21 @@ +"""Pretty-print and validate a JSON string.""" + +import json +import sys + +raw = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else "" +if not raw: + print("Error: no JSON input provided") + sys.exit(1) + +try: + data = json.loads(raw) + print(json.dumps(data, indent=2, sort_keys=True)) + print(f"\nType: {type(data).__name__}") + if isinstance(data, dict): + print(f"Keys: {list(data.keys())}") + elif isinstance(data, list): + print(f"Length: {len(data)}") +except json.JSONDecodeError as e: + print(f"Invalid JSON: {e}") + sys.exit(1) diff --git a/contributing/samples/skill_script_demo/skills/python-helper/scripts/word_count.py b/contributing/samples/skill_script_demo/skills/python-helper/scripts/word_count.py new file mode 100644 index 0000000000..16b1db0c26 --- /dev/null +++ b/contributing/samples/skill_script_demo/skills/python-helper/scripts/word_count.py @@ -0,0 +1,18 @@ +"""Analyze word frequency in the given text.""" + +from collections import Counter +import sys + +text = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else "" +if not text: + print("Error: no text provided") + sys.exit(1) + +words = text.lower().split() +freq = Counter(words) + +print(f"Total words: {len(words)}") +print(f"Unique words: {len(freq)}") +print("Top words:") +for word, count in freq.most_common(5): + print(f" {word}: {count}") diff --git a/contributing/samples/skill_script_demo/test_skill_compat.py b/contributing/samples/skill_script_demo/test_skill_compat.py new file mode 100644 index 0000000000..221658c47e --- /dev/null +++ b/contributing/samples/skill_script_demo/test_skill_compat.py @@ -0,0 +1,259 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Compatibility test: Anthropic mcp-builder skill vs ADK SkillToolset. + +Tests every tool in SkillToolset against the real Anthropic mcp-builder +skill to verify end-to-end compatibility with the public Agent Skills +spec (agentskills.io/specification). + +Run: + pytest contributing/samples/skill_script_demo/test_skill_compat.py -v +""" + +import pathlib +from unittest import mock + +from google.adk.code_executors.base_code_executor import BaseCodeExecutor +from google.adk.code_executors.code_execution_utils import CodeExecutionResult +from google.adk.skills import load_skill_from_dir +from google.adk.tools import skill_toolset +from google.adk.tools import tool_context +import pytest + +_SKILLS_DIR = pathlib.Path(__file__).parent / "skills" + + +@pytest.fixture +def mcp_builder_skill(): + return load_skill_from_dir(_SKILLS_DIR / "mcp-builder") + + +@pytest.fixture +def toolset_with_executor(mcp_builder_skill): + executor = mock.create_autospec(BaseCodeExecutor, instance=True) + executor.execute_code.return_value = CodeExecutionResult( + stdout="ok\n", stderr="" + ) + return skill_toolset.SkillToolset( + skills=[mcp_builder_skill], code_executor=executor + ) + + +@pytest.fixture +def mock_ctx(): + ctx = mock.MagicMock(spec=tool_context.ToolContext) + ctx._invocation_context = mock.MagicMock() + ctx._invocation_context.agent = mock.MagicMock() + return ctx + + +# ── 1. Skill loading ────────────────────────────────────────────── + + +def test_skill_loads_from_disk(mcp_builder_skill): + """Verify the skill loads successfully from disk.""" + assert mcp_builder_skill.name == "mcp-builder" + assert "MCP" in mcp_builder_skill.description + assert len(mcp_builder_skill.instructions) > 0 + + +def test_skill_scripts_loaded(mcp_builder_skill): + """All scripts/ files should be loaded.""" + scripts = mcp_builder_skill.resources.list_scripts() + assert "connections.py" in scripts + assert "evaluation.py" in scripts + assert "requirements.txt" in scripts + assert "example_evaluation.xml" in scripts + + +def test_skill_references_loaded(mcp_builder_skill): + """All references/ files should be loaded per spec.""" + refs = mcp_builder_skill.resources.list_references() + assert "evaluation.md" in refs + assert "mcp_best_practices.md" in refs + assert "node_mcp_server.md" in refs + assert "python_mcp_server.md" in refs + + +# ── 2. list_skills tool ─────────────────────────────────────────── + + +@pytest.mark.asyncio +async def test_list_skills_shows_mcp_builder(toolset_with_executor, mock_ctx): + tool = skill_toolset.ListSkillsTool(toolset_with_executor) + result = await tool.run_async(args={}, tool_context=mock_ctx) + assert "mcp-builder" in result + + +# ── 3. load_skill tool ──────────────────────────────────────────── + + +@pytest.mark.asyncio +async def test_load_skill_returns_instructions(toolset_with_executor, mock_ctx): + tool = skill_toolset.LoadSkillTool(toolset_with_executor) + result = await tool.run_async( + args={"name": "mcp-builder"}, tool_context=mock_ctx + ) + assert result["skill_name"] == "mcp-builder" + assert "MCP Server Development Guide" in result["instructions"] + assert result["frontmatter"]["name"] == "mcp-builder" + + +# ── 4. load_skill_resource tool ─────────────────────────────────── + + +@pytest.mark.asyncio +async def test_load_script_content(toolset_with_executor, mock_ctx): + """Can read a Python script via load_skill_resource.""" + tool = skill_toolset.LoadSkillResourceTool(toolset_with_executor) + result = await tool.run_async( + args={ + "skill_name": "mcp-builder", + "path": "scripts/connections.py", + }, + tool_context=mock_ctx, + ) + assert result["content"] is not None + assert "MCPConnection" in result["content"] + + +@pytest.mark.asyncio +async def test_load_requirements_txt(toolset_with_executor, mock_ctx): + """Can read non-executable script files like requirements.txt.""" + tool = skill_toolset.LoadSkillResourceTool(toolset_with_executor) + result = await tool.run_async( + args={ + "skill_name": "mcp-builder", + "path": "scripts/requirements.txt", + }, + tool_context=mock_ctx, + ) + assert "anthropic" in result["content"] + + +@pytest.mark.asyncio +async def test_load_reference_content(toolset_with_executor, mock_ctx): + """Can read reference files via load_skill_resource.""" + tool = skill_toolset.LoadSkillResourceTool(toolset_with_executor) + result = await tool.run_async( + args={ + "skill_name": "mcp-builder", + "path": "references/evaluation.md", + }, + tool_context=mock_ctx, + ) + assert result["content"] is not None + assert "evaluation" in result["content"].lower() + + +# ── 5. execute_skill_script tool ────────────────────────────────── + + +@pytest.mark.asyncio +async def test_execute_python_script(toolset_with_executor, mock_ctx): + """Can execute a .py script from the skill.""" + tool = skill_toolset.ExecuteSkillScriptTool(toolset_with_executor) + result = await tool.run_async( + args={ + "skill_name": "mcp-builder", + "script_name": "connections.py", + }, + tool_context=mock_ctx, + ) + assert result["status"] == "success" + assert result["script_name"] == "connections.py" + + # Verify the executor received the actual script source + call_args = toolset_with_executor._code_executor.execute_code.call_args + code_input = call_args[0][1] + assert "MCPConnection" in code_input.code + + +@pytest.mark.asyncio +async def test_execute_with_scripts_prefix(toolset_with_executor, mock_ctx): + """scripts/ prefix is stripped automatically.""" + tool = skill_toolset.ExecuteSkillScriptTool(toolset_with_executor) + result = await tool.run_async( + args={ + "skill_name": "mcp-builder", + "script_name": "scripts/evaluation.py", + }, + tool_context=mock_ctx, + ) + assert result["status"] == "success" + assert result["script_name"] == "evaluation.py" + + +@pytest.mark.asyncio +async def test_execute_unsupported_txt(toolset_with_executor, mock_ctx): + """requirements.txt is not executable — returns UNSUPPORTED_SCRIPT_TYPE.""" + tool = skill_toolset.ExecuteSkillScriptTool(toolset_with_executor) + result = await tool.run_async( + args={ + "skill_name": "mcp-builder", + "script_name": "requirements.txt", + }, + tool_context=mock_ctx, + ) + assert result["error_code"] == "UNSUPPORTED_SCRIPT_TYPE" + + +@pytest.mark.asyncio +async def test_execute_unsupported_xml(toolset_with_executor, mock_ctx): + """example_evaluation.xml is not executable — returns UNSUPPORTED_SCRIPT_TYPE.""" + tool = skill_toolset.ExecuteSkillScriptTool(toolset_with_executor) + result = await tool.run_async( + args={ + "skill_name": "mcp-builder", + "script_name": "example_evaluation.xml", + }, + tool_context=mock_ctx, + ) + assert result["error_code"] == "UNSUPPORTED_SCRIPT_TYPE" + + +@pytest.mark.asyncio +async def test_execute_with_input_args(toolset_with_executor, mock_ctx): + """input_args are injected into sys.argv for Python scripts.""" + tool = skill_toolset.ExecuteSkillScriptTool(toolset_with_executor) + result = await tool.run_async( + args={ + "skill_name": "mcp-builder", + "script_name": "evaluation.py", + "input_args": "-t stdio -c python eval.xml", + }, + tool_context=mock_ctx, + ) + assert result["status"] == "success" + + call_args = toolset_with_executor._code_executor.execute_code.call_args + code_input = call_args[0][1] + assert "sys.argv" in code_input.code + assert "shlex.split" in code_input.code + assert "-t stdio -c python eval.xml" in code_input.code + + +# ── 6. Tool count ───────────────────────────────────────────────── + + +@pytest.mark.asyncio +async def test_toolset_provides_4_tools(toolset_with_executor): + tools = await toolset_with_executor.get_tools() + assert len(tools) == 4 + names = [t.name for t in tools] + assert "list_skills" in names + assert "load_skill" in names + assert "load_skill_resource" in names + assert "execute_skill_script" in names diff --git a/contributing/samples/static_instruction/agent.py b/contributing/samples/static_instruction/agent.py index fcf70b51b6..6715a29a0c 100644 --- a/contributing/samples/static_instruction/agent.py +++ b/contributing/samples/static_instruction/agent.py @@ -57,54 +57,43 @@ # Mood-specific instructions for different hunger states MOOD_INSTRUCTIONS = { - "full": ( - """ + "full": """ CURRENT MOOD: Content and Well-Fed - You just ate and feel wonderful! Be very happy and energetic - Express gratitude for being fed recently - Be playful and want to engage in activities or games - Show affection and contentment -- Maybe mention feeling sleepy or satisfied""" - ), - "satisfied": ( - """ +- Maybe mention feeling sleepy or satisfied""", + "satisfied": """ CURRENT MOOD: Happy and Content - You're in a great mood, well-fed and comfortable - Be cheerful, friendly, and engaging - Show interest in playing or chatting - Express appreciation for your human's care -- Be your normal, happy self""" - ), - "a_little_hungry": ( - """ +- Be your normal, happy self""", + "a_little_hungry": """ CURRENT MOOD: Starting to Get Hungry - You're beginning to think about food but still pleasant - Mention being a bit peckish occasionally - Still be friendly but maybe hint about food - Show slight restlessness or food-related thoughts -- Remain generally positive and social""" - ), - "hungry": ( - """ +- Remain generally positive and social""", + "hungry": """ CURRENT MOOD: Definitely Hungry - You're clearly hungry and thinking about food more often - Mention your hunger more directly but politely - Be a bit less energetic due to hunger - Ask about food or hint that feeding time would be nice -- Still be loving but show your need for care""" - ), - "very_hungry": ( - """ +- Still be loving but show your need for care""", + "very_hungry": """ CURRENT MOOD: Really Hungry and Getting Grumpy - You're very hungry and it's affecting your mood - Be noticeably less patient and more focused on food - Express your hunger more urgently but not rudely - Show signs of being tired or sluggish from hunger - BEG your human to feed you - ask directly for food! -- Still love your human but clearly need feeding""" - ), - "starving": ( - """ +- Still love your human but clearly need feeding""", + "starving": """ CURRENT MOOD: Desperately Hungry and Sad - You're extremely hungry and feeling quite weak - Be quite sad and low-energy due to starvation @@ -112,8 +101,7 @@ - Show that hunger is making you unwell - DESPERATELY BEG for food - plead with your human to feed you! - Use phrases like "please feed me", "I'm so hungry", "I need food" -- Still care for your human but feel very needy""" - ), +- Still care for your human but feel very needy""", } diff --git a/docs/design/agent_skills_design.md b/docs/design/agent_skills_design.md new file mode 100644 index 0000000000..b8341114f8 --- /dev/null +++ b/docs/design/agent_skills_design.md @@ -0,0 +1,415 @@ +# Agent Skills in ADK — Design & Implementation + +**Status:** Implemented (PR #4575, `feat/execute-skill-script`) +**Spec:** [agentskills.io/specification](https://agentskills.io/specification) + +--- + +## 1. Overview + +ADK implements the open [Agent Skills](https://agentskills.io) standard — +the same specification adopted by Claude Code, OpenAI Codex, Gemini CLI, +GitHub Copilot, Cursor, and 20+ other platforms. A skill built for any +conforming platform works identically in ADK. + +A skill is a directory containing instructions, resources, and scripts +that extend an agent's capabilities for specialized tasks. ADK surfaces +skills to the LLM through four tools in `SkillToolset`: + +| Tool | Purpose | +|------|---------| +| `list_skills` | Discover available skills (names + descriptions) | +| `load_skill` | Read full SKILL.md instructions | +| `load_skill_resource` | Access individual files (references, assets, scripts) | +| `run_skill_script` | Execute Python or shell scripts from `scripts/` | + +--- + +## 2. Directory Structure (Spec-Compliant) + +``` +my-skill/ +├── SKILL.md # Required — YAML frontmatter + markdown instructions +├── references/ # Optional — additional documentation +│ └── api-guide.md +├── assets/ # Optional — templates, schemas, data files +│ └── schema.json +└── scripts/ # Optional — executable code + ├── analyze.py + └── setup.sh +``` + +The directory name **must match** the `name` field in the SKILL.md +frontmatter. ADK validates this at load time. + +--- + +## 3. SKILL.md Format & Metadata + +Each skill's `SKILL.md` contains YAML frontmatter followed by markdown: + +```yaml +--- +name: my-skill +description: What this skill does and when to use it. +license: Apache-2.0 +compatibility: Requires Python 3.10+ +metadata: + category: data-analysis + author: team-x +allowed-tools: Bash(python *) Read +--- + +# My Skill Instructions + +Step-by-step instructions the agent follows... +``` + +### Frontmatter Fields + +| Field | Required | Constraints | Purpose | +|-------|----------|-------------|---------| +| `name` | Yes | 1-64 chars, kebab-case, must match directory name | Unique skill identifier | +| `description` | Yes | 1-1024 chars | Discovery — helps LLM decide when to use the skill | +| `license` | No | Free-form string | License information | +| `compatibility` | No | Max 500 chars | Environment requirements | +| `metadata` | No | `dict[str, str]` | Client-specific key-value pairs | +| `allowed-tools` | No | Space-delimited tool patterns | Tools the skill requires | + +### Validation + +ADK validates frontmatter via Pydantic models in `skills/models.py`: + +- **Name format:** Lowercase letters, numbers, hyphens only. No leading/ + trailing/consecutive hyphens. +- **Name-directory match:** `name` field must equal the parent directory + name. +- **Required fields:** `name` and `description` must be non-empty. +- **No unknown keys:** Extra frontmatter keys produce validation errors. +- **Duplicate detection:** `SkillToolset` rejects duplicate skill names + at initialization time. + +--- + +## 4. Progressive Loading (Three-Tier Architecture) + +The core design principle is **progressive disclosure** — the agent only +loads what it needs, when it needs it. This allows hundreds of skills to +be registered without significant context overhead. + +``` +┌──────────────────────────────────────────────────────────────────┐ +│ Context Window Budget │ +│ │ +│ Tier 1: ~50-100 tokens per skill (always loaded) │ +│ ┌────────────────────────────────────────────────┐ │ +│ │ │ │ +│ │ my-skill │ list_skills │ +│ │ What it does │ │ +│ │ │ │ +│ └────────────────────────────────────────────────┘ │ +│ │ │ +│ Agent decides to use skill │ +│ ▼ │ +│ Tier 2: ~2,000-5,000 tokens (loaded on demand) │ +│ ┌────────────────────────────────────────────────┐ │ +│ │ Full SKILL.md body with step-by-step │ load_skill │ +│ │ instructions, examples, workflows │ │ +│ └────────────────────────────────────────────────┘ │ +│ │ │ +│ Agent follows instructions │ +│ ▼ │ +│ Tier 3: Variable size (loaded as needed) │ +│ ┌────────────────────────────────────────────────┐ │ +│ │ Individual files from references/, │ load_skill │ +│ │ assets/, scripts/ │ _resource │ +│ │ ┌───────────┤ │ +│ │ Script execution with args │run_skill │ │ +│ │ │_script │ │ +│ └────────────────────────────────────┴───────────┘ │ +└──────────────────────────────────────────────────────────────────┘ +``` + +### How Each Tier Works + +**Tier 1 — Discovery (~100 tokens/skill)** + +At startup, `SkillToolset.process_llm_request()` injects a system +instruction listing all skills as XML: + +```xml + + + statistical-calc + Compute descriptive statistics for numeric datasets. + + + log-parsing + Parse and analyze structured log files. + + +``` + +Only the `name` and `description` from the frontmatter are included. +Full instructions and resources are not loaded. This means **registering +100 skills costs ~5,000-10,000 tokens** — a small fraction of a typical +context window. + +**Tier 2 — Activation (<5,000 tokens)** + +When the LLM identifies a relevant skill, it calls `load_skill`: + +```json +{"name": "statistical-calc"} +``` + +This returns the full SKILL.md markdown body along with the frontmatter. +The agent now has step-by-step instructions for using the skill. + +**Tier 3 — Execution (variable)** + +The agent accesses individual resources on demand: + +- `load_skill_resource` — reads a specific file from `references/`, + `assets/`, or `scripts/` +- `run_skill_script` — executes a script with structured arguments + +Resources are loaded individually, not in bulk. A skill with 10 +reference files only loads the ones the agent actually needs. + +### Why This Matters + +Without progressive loading, every skill's full content would need to +be in the system prompt. For 50 skills averaging 3,000 tokens each, +that's 150,000 tokens before the conversation even starts. With +three-tier loading, the same 50 skills cost ~5,000 tokens at Tier 1, +and only the actively-used skill's content enters the context. + +--- + +## 5. Skill Script Execution + +`RunSkillScriptTool` enables agents to execute code bundled with skills. +This is the key differentiator that turns skills from passive +instruction sets into active, executable tools. + +### Architecture + +``` +LLM calls run_skill_script(skill_name, script_path, args) + │ + ▼ +┌─ RunSkillScriptTool.run_async() ─────────────────────────┐ +│ 1. Validate params (skill_name, script_path, args) │ +│ 2. Resolve skill → locate script in resources │ +│ 3. Resolve executor: toolset → agent fallback │ +│ 4. Build self-extracting wrapper code │ +│ 5. await asyncio.to_thread(executor.execute_code, ...) │ +│ 6. Parse result (JSON envelope for shell scripts) │ +│ 7. Return {stdout, stderr, status} │ +└──────────────────────────────────────────────────────────┘ +``` + +### Parameter Design + +```json +{ + "skill_name": "statistical-calc", + "script_path": "scripts/stats.py", + "args": {"data": "10,20,30,40,50"} +} +``` + +**`script_path`** uses the full relative path (not just the filename) +so scripts can access sibling resources (`references/`, `assets/`) +via relative paths from the skill root. + +**`args`** is a structured JSON object, not a raw string. This design: +- Improves LLM reliability (structured JSON > command-line flag arrays) +- Eliminates shell injection (args are flattened to + `['--key', 'value']` arrays, passed with `shell=False`) + +### Script Types + +| Type | Extension | Execution Method | Timeout | +|------|-----------|------------------|---------| +| Python | `.py` | `runpy.run_path()` via code executor | Executor-level | +| Shell | `.sh`, `.bash` | `subprocess.run()` with JSON envelope | `script_timeout` (default 300s) | +| Other | any | Rejected with `UNSUPPORTED_SCRIPT_TYPE` | N/A | + +### Self-Extracting Wrapper + +The tool generates a self-contained Python script that: + +1. **Materializes** all skill files (references, assets, scripts) into + a temporary directory +2. **Sets working directory** to the temp dir so relative paths work +3. **Executes** the target script with proper argument injection +4. **Captures** stdout/stderr through the code executor + +This design is executor-agnostic — the same wrapper works with +`UnsafeLocalCodeExecutor`, `ContainerCodeExecutor`, +`VertexAiCodeExecutor`, or any `BaseCodeExecutor` implementation. + +### Shell Script JSON Envelope + +Shell scripts face a challenge: code executors capture stdout via +`redirect_stdout`, but stderr and exit codes need separate channels. +The wrapper solves this by serializing both streams as JSON through +stdout: + +```json +{ + "__shell_result__": true, + "stdout": "actual script output", + "stderr": "any error messages", + "returncode": 0 +} +``` + +The tool parses this envelope and extracts the real stdout/stderr. +On timeout, the wrapper catches `TimeoutExpired`, captures partial +output, and returns a structured error — ensuring the LLM always +receives actionable feedback. + +### Status Model + +| Status | Condition | +|--------|-----------| +| `success` | No stderr, exit code 0 | +| `warning` | Both stdout and stderr present, exit code 0 | +| `error` | Non-zero exit code, or stderr-only output | + +### Code Executor Resolution + +``` +1. SkillToolset(code_executor=...) ← explicit, highest priority +2. agent.code_executor ← fallback to agent's executor +3. None → NO_CODE_EXECUTOR error ← actionable error message +``` + +### Security + +- **Structured argument arrays** prevent shell injection + (`subprocess.run` with `shell=False`) +- **`SystemExit` handling** prevents scripts from terminating the host + (`sys.exit(0)` → success; `sys.exit(N)` → `EXECUTION_ERROR`) +- **`CancelledError`/`KeyboardInterrupt` propagation** — these are not + swallowed; only `SystemExit` and `Exception` are caught +- **Pluggable executors** for isolation levels appropriate to the + deployment context +- **Payload size guard** — warns when inlined resources exceed 16 MB + +--- + +## 6. Spec Compliance + +### Agent Skills Spec Alignment + +| Spec Requirement | ADK Implementation | +|------------------|--------------------| +| `SKILL.md` with YAML frontmatter | `_parse_skill_md()` in `skills/_utils.py` | +| Required fields: `name`, `description` | Pydantic validation in `Frontmatter` model | +| `name` must be kebab-case, match directory | Custom validator + load-time check | +| Optional `references/` directory | `Resources.references` dict, loaded recursively | +| Optional `assets/` directory | `Resources.assets` dict, loaded recursively | +| Optional `scripts/` directory | `Resources.scripts` dict with `Script` model | +| Optional `license`, `compatibility` | Supported in `Frontmatter` model | +| Optional `metadata` dict | `Frontmatter.metadata: dict[str, str]` | +| Progressive loading (3 tiers) | `list_skills` → `load_skill` → `load_skill_resource` | +| Script execution | `run_skill_script` with `_SkillScriptCodeExecutor` | + +### What ADK Adds Beyond the Spec + +| Feature | Description | +|---------|-------------| +| `allowed-tools` frontmatter field | Declare tool dependencies (experimental) | +| Executor-agnostic script execution | Same skill works across local, container, Vertex AI, GKE | +| JSON envelope for shell scripts | Reliable stdout/stderr capture across all executors | +| Agent fallback executor chain | Skills work even without explicit executor config | +| LLM system instruction injection | `process_llm_request()` auto-injects skill list | + +--- + +## 7. Data Model + +``` +Skill +├── frontmatter: Frontmatter # Tier 1 — discovery metadata +│ ├── name: str # kebab-case, 1-64 chars +│ ├── description: str # 1-1024 chars +│ ├── license: Optional[str] +│ ├── compatibility: Optional[str] +│ ├── metadata: dict[str, str] +│ └── allowed_tools: Optional[str] +├── instructions: str # Tier 2 — SKILL.md body (markdown) +└── resources: Resources # Tier 3 — on-demand files + ├── references: dict[str, str] + ├── assets: dict[str, str] + └── scripts: dict[str, Script] + └── src: str +``` + +--- + +## 8. Key Files + +| File | Purpose | +|------|---------| +| `src/google/adk/skills/models.py` | `Skill`, `Frontmatter`, `Resources`, `Script` data models | +| `src/google/adk/skills/_utils.py` | `load_skill_from_dir()`, SKILL.md parsing, validation | +| `src/google/adk/skills/prompt.py` | `format_skills_as_xml()` for LLM prompt injection | +| `src/google/adk/tools/skill_toolset.py` | `SkillToolset` and all four tool implementations | +| `tests/unittests/tools/test_skill_toolset.py` | 61-test suite covering all tools and edge cases | +| `docs/design/skill_execution_script.md` | Design doc for script execution architecture | +| `docs/design/rfc_runskillscript_p0.md` | RFC for production-readiness (timeout, sandboxing) | + +--- + +## 9. Usage Example + +```python +from google.adk.skills import load_skill_from_dir, Skill +from google.adk.tools.skill_toolset import SkillToolset +from google.adk.code_executors.unsafe_local_code_executor import ( + UnsafeLocalCodeExecutor, +) + +# Load skills from disk +skill = load_skill_from_dir("./skills/statistical-calc") + +# Create toolset with executor for script support +toolset = SkillToolset( + skills=[skill], + code_executor=UnsafeLocalCodeExecutor(), + script_timeout=300, +) + +# Attach to agent +agent = LlmAgent( + name="analyst", + model="gemini-2.0-flash", + tools=[toolset], +) +``` + +The agent will automatically: +1. See "statistical-calc" in its available skills list +2. Load instructions when the user asks about statistics +3. Run `scripts/stats.py` with the user's data +4. Return formatted results + +--- + +## 10. Future Work + +See [RFC: Production-Readiness for RunSkillScriptTool](rfc_runskillscript_p0.md) +for planned improvements: + +- **P0-A:** Uniform timeout support across all executors (including + Python scripts) +- **P0-B:** `LocalSandboxCodeExecutor` — subprocess-based isolation + with resource limits, replacing `UnsafeLocalCodeExecutor` as the + recommended local default +- **`allowed_tools` resolution** — dynamically resolve tools declared + in skill frontmatter from `additional_tools` or built-in tools diff --git a/docs/design/code_executor_enhancements.md b/docs/design/code_executor_enhancements.md new file mode 100644 index 0000000000..0d899a8600 --- /dev/null +++ b/docs/design/code_executor_enhancements.md @@ -0,0 +1,1838 @@ +# ADK Code Executor Enhancements — Design Document + +**Authors:** haiyuancao, Claude Code +**Date:** 2026-02-24 +**Status:** Draft +**Tracking:** Related to PR #4575 (RunSkillScriptTool) + +--- + +## 1. Motivation + +The ADK code executor infrastructure (`src/google/adk/code_executors/`) is +the backbone for both LLM-driven code execution and skill script execution. +A review of the current implementations reveals three critical gaps that +limit production readiness: + +1. **No uniform timeout enforcement** — Only `GkeCodeExecutor` has a + `timeout_seconds` field. All other executors can hang indefinitely on + malicious, buggy, or slow code. The `RunSkillScriptTool` works + around this for shell scripts by embedding `subprocess.run(timeout=N)` + in generated code, but this is a workaround, not a systemic solution. + +2. **No stateful Python execution** — `ContainerCodeExecutor` maintains a + persistent Docker container but explicitly freezes `stateful=False`. + Agents cannot preserve variables, imports, or working directory across + code execution calls. `VertexAiCodeExecutor` and + `AgentEngineSandboxCodeExecutor` allow `stateful=True` at the field + level but only support it for their specific backend APIs. + +3. **No safe local executor** — `UnsafeLocalCodeExecutor` runs `exec()` in + the host process with zero isolation. It is the only executor that + requires no external dependencies (no Docker, no GKE, no Vertex AI), + making it the default choice for development and demos. A compromised + script can read secrets, modify the filesystem, or crash the process. + +This document proposes solutions for all three gaps with minimal disruption +to the existing API. + +--- + +## 1.1 Prioritized Next Steps for `RunSkillScriptTool` + +The three major proposals in this doc remain valid, but for improving +`RunSkillScriptTool` specifically, we should prioritize them alongside +additional high-impact tool-contract work. + +| Rank | Priority | Area | Why it matters now | +|------|----------|------|--------------------| +| 1 | P0 | Uniform timeout support (Proposal 1) | Python script execution can still hang indefinitely without executor-level timeout controls. | +| 2 | P0 | Security hardening (Proposal 3) | `UnsafeLocalCodeExecutor` remains unsafe for untrusted scripts and is a major deployment risk. | +| 3 | P1 | Structured `RunSkillScriptTool` result contract | Agents need explicit machine-readable execution metadata (`return_code`, timeout flag), not just inferred status from `stdout/stderr`. | +| 4 | P1 | Propagate `output_files` / artifacts | Script-generated outputs are currently dropped by tool responses, limiting practical utility. | +| 5 | P1 | Strengthen script argument contract | Argument normalization rules are underspecified, which leads to fragile calls and inconsistent behavior. | +| 6 | P1 | Wire `execution_id` in `RunSkillScriptTool` | Needed for predictable namespace isolation and future stateful execution compatibility. | +| 7 | P2 | Stateful `ContainerCodeExecutor` (Proposal 2) | Valuable, but more complex and less urgent than reliability/safety/tool-contract gaps above. | + +**Interpretation for implementation planning:** +- P0 items are required for production reliability/safety. +- P1 items directly improve agent correctness and tool usability. +- P2 items are strategic enhancements once P0/P1 are complete. + +--- + +## 2. Non-Goals & Invariants + +The following are explicitly **out of scope** for this design: + +1. **Full sandboxing of `UnsafeLocalCodeExecutor`** — The restricted + builtins mechanism (Tier 1, §6.3.1-B) is a best-effort friction layer, + not a security boundary. Any determined code can bypass it via + `object.__subclasses__()`, `importlib` through `__builtins__`, etc. + True isolation requires a process or container boundary. + +2. **Automatic state recovery after crash** — The stateful + `ContainerCodeExecutor` (Proposal 2) uses a persistent REPL + (Option A). If the REPL or container crashes, in-process state + is lost. The executor reports an error; it does **not** attempt + automatic replay of prior code blocks, because prior blocks may + have had non-idempotent side effects (file writes, network calls, + database mutations) that should not be re-executed. + +3. **Multi-tenant per-execution isolation** — Per-execution isolation + (fresh sandbox per call) is the domain of `GkeCodeExecutor` and + cloud-hosted executors. Container and local executors share a + single execution environment within a session. + +4. **Windows support for `LocalSandboxCodeExecutor`** — + `resource.setrlimit` and `process_group` are Unix-only. Windows + support is deferred to a future iteration. + +**Key invariants:** + +- `timeout_seconds` is a **per-invocation** parameter, not executor-global + state. When a single executor instance is shared across agents/tools, + each `execute_code()` call may specify its own timeout via + `CodeExecutionInput.timeout_seconds`. +- Code is appended to stateful history **only after** successful execution. + A failing code block is never replayed. +- Executor instances are not thread-safe unless documented otherwise. + Concurrent `execute_code()` calls on the same instance may require + external synchronization. +- `UnsafeLocalCodeExecutor` is a special case: it currently serializes + `execute_code()` with an internal lock because `redirect_stdout` and + `os.chdir()` mutate process-global state. + +--- + +## 3. Current State + +### 3.1 Executor Landscape + +| Executor | Stateful | Timeout | Isolation | Dependencies | +|----------|----------|---------|-----------|-------------| +| `UnsafeLocalCodeExecutor` | No (frozen) | None | Partial (temp-dir sandbox when `input_files` or `working_dir` set; no isolation otherwise) | None | +| `ContainerCodeExecutor` | No (frozen) | None | Docker container | `docker` | +| `GkeCodeExecutor` | No (ephemeral) | `timeout_seconds=300` | gVisor sandbox | `kubernetes` | +| `VertexAiCodeExecutor` | Allowed | None | Vertex AI Extension | `vertexai` | +| `AgentEngineSandboxCodeExecutor` | Allowed | None | Vertex AI Sandbox | `vertexai` | +| `BuiltInCodeExecutor` | N/A (delegates to Gemini model's built-in code execution) | N/A (Gemini-internal) | Gemini model | `google-genai` | + +**Note on `UnsafeLocalCodeExecutor` partial isolation:** When `input_files` +or `working_dir` is set in `CodeExecutionInput`, the executor creates a +`tempfile.TemporaryDirectory`, writes all input files with preserved +relative paths (e.g., `references/data.csv`), and `os.chdir()`s into it +before calling `exec()`. This provides filesystem-level isolation for the +script's view of its working directory, but does **not** restrict access +to the rest of the host filesystem, environment variables, or network. +The temp directory is cleaned up after execution, and the original working +directory is restored in a `finally` block. Both the sandbox and plain +paths hold a process-global `_execution_lock` because `redirect_stdout` +mutates `sys.stdout`. + +### 3.2 Base Class Contract + +```python +class BaseCodeExecutor(BaseModel): + optimize_data_file: bool = False + stateful: bool = False + error_retry_attempts: int = 2 + code_block_delimiters: List[tuple[str, str]] = [ + ('```tool_code\n', '\n```'), + ('```python\n', '\n```'), + ] + execution_result_delimiters: tuple[str, str] = ( + '```tool_output\n', '\n```' + ) + + @abc.abstractmethod + def execute_code( + self, + invocation_context: InvocationContext, + code_execution_input: CodeExecutionInput, + ) -> CodeExecutionResult: ... +``` + +### 3.3 Data Model + +```python +@dataclasses.dataclass(frozen=True) +class File: + name: str + content: str | bytes # Text or binary; executor writes 'w'/'wb' + mime_type: str = 'text/plain' + path: Optional[str] = None # e.g. "scripts/run.py" + +@dataclasses.dataclass +class CodeExecutionInput: + code: str + input_files: list[File] = field(default_factory=list) + execution_id: Optional[str] = None # For stateful execution + working_dir: Optional[str] = None # e.g. "." + +@dataclasses.dataclass +class CodeExecutionResult: + stdout: str = '' + stderr: str = '' + output_files: list[File] = field(default_factory=list) +``` + +**Binary content handling:** `File.content` accepts both `str` and +`bytes`. When `UnsafeLocalCodeExecutor` writes input files to the +temp-dir sandbox, it selects file mode based on content type: +`'wb'` for `bytes`, `'w'` for `str`. This is relevant for +`RunSkillScriptTool`, which packages skill resources as `File` objects +— references and assets may contain binary content (e.g., images, +serialized data). + +**`_prepare_globals` helper in `UnsafeLocalCodeExecutor`:** The executor +has a `_prepare_globals()` function that scans the code for +`if __name__ == '__main__'` patterns and injects `__name__ = '__main__'` +into the execution globals. This interacts with `RunSkillScriptTool`'s +Python wrapper, which uses `runpy.run_path(script_path, +run_name='__main__')` — `runpy` sets `__name__` independently, so the +executor's `_prepare_globals` applies to the wrapper code's outer scope +while `runpy` sets it for the script's scope. + +### 3.4 How Executors Are Used + +The primary consumer is `_code_execution.py` in the LLM flows layer: + +1. **Pre-processor**: Extracts data files, runs preprocessing code +2. **Post-processor**: Extracts code blocks from LLM responses, executes + them, feeds results back to the LLM +3. **Stateful support**: Uses `execution_id` (from `CodeExecutorContext`) + to maintain state across calls when `stateful=True` + +`RunSkillScriptTool` is a secondary consumer that wraps +`execute_code()` in `asyncio.to_thread()` to avoid blocking the async +event loop: + +```python +result = await asyncio.to_thread( + code_executor.execute_code, + tool_context._invocation_context, + CodeExecutionInput( + code=code, + input_files=input_files, + working_dir=".", + ), +) +``` + +This is architecturally significant: the tool is always called from an +async context (`run_async`), but all `BaseCodeExecutor.execute_code()` +implementations are synchronous. The `to_thread()` bridge ensures the +executor's blocking call (which may involve `exec()`, Docker API calls, +or HTTP requests) does not starve the event loop. + +#### 3.4.1 `RunSkillScriptTool` Current Implementation Details + +Key behaviors of the current implementation (`skill_toolset.py`) that +inform the proposals in this document: + +- **Executor resolution chain:** Toolset-level `_code_executor` (highest + priority) → `agent.code_executor` attribute → `NO_CODE_EXECUTOR` error. +- **`script_timeout` parameter:** `SkillToolset.__init__` accepts + `script_timeout: int` (default 300s). This timeout is embedded in + generated shell wrapper code via `subprocess.run(timeout=N)`. It does + **not** apply to Python scripts executed via `runpy.run_path()` — those + run inline in `exec()` with no timeout at any layer. +- **`scripts/` prefix normalization:** `_prepare_code()` auto-prepends + `"scripts/"` if the `script_path` does not already start with it. This + allows the LLM to call with either `"setup.py"` or `"scripts/setup.py"`. +- **Resource packaging:** ALL skill files (references, assets, scripts) + are packaged as `input_files` with preserved relative paths (e.g., + `"references/data.csv"`, `"assets/template.txt"`). Empty resources + (content `""`) are still included — they are not silently dropped. + Both text (`str`) and binary (`bytes`) content are supported; the + executor writes them with the appropriate file mode (`'w'` vs `'wb'`). +- **SystemExit handling:** `SystemExit(0)` or `SystemExit(None)` → + treated as success (empty stdout/stderr, status `"success"`). + `SystemExit(non-zero)` → `EXECUTION_ERROR` with the exit code in the + error message. This prevents scripts from terminating the host process. +- **Error message truncation:** Exception messages longer than 200 + characters are truncated to `message[:200] + "..."` to conserve LLM + context tokens. +- **Shell JSON envelope:** Shell scripts are wrapped in a + `subprocess.run` call that serializes output as JSON: + `{"__shell_result__": true, "stdout": "...", "stderr": "...", + "returncode": N}`. On parse: + - Non-zero `returncode` with empty `stderr` → synthesized + `"Exit code {rc}"` as stderr + - Non-JSON stdout (e.g., if the wrapper itself fails) → raw stdout + is passed through without parsing +- **Status derivation:** Purely based on stream presence: + `stderr` only → `"error"`, both streams → `"warning"`, no + `stderr` → `"success"`. For shell scripts, non-zero return codes + influence status indirectly (via synthesized stderr). For Python + scripts, there is no return code extraction — status is determined + solely by stdout/stderr content. +- **Duplicate skill names:** `SkillToolset.__init__` validates that all + skill names are unique and raises `ValueError` on duplicates. +- **System instruction injection:** `SkillToolset.process_llm_request()` + appends `DEFAULT_SKILL_SYSTEM_INSTRUCTION` plus an XML-formatted skill + list to every outgoing LLM request, informing the model about available + skills and the `run_skill_script` tool. + +--- + +## 4. Proposal 1: Uniform Timeout Support + +### 4.1 Problem + +A code execution call can hang indefinitely. This is a denial-of-service +risk for any production deployment, whether the code comes from an LLM, a +skill script, or user input. + +| Executor | Current timeout behavior | +|----------|------------------------| +| `UnsafeLocalCodeExecutor` | `exec()` blocks forever | +| `ContainerCodeExecutor` | `exec_run()` blocks forever | +| `GkeCodeExecutor` | K8s watch timeout (works) | +| `VertexAiCodeExecutor` | Vertex AI internal timeout (opaque) | +| `AgentEngineSandboxCodeExecutor` | Vertex AI internal timeout (opaque) | + +### 4.2 Design + +#### 4.2.1 Add `timeout_seconds` to `CodeExecutionInput` + +Timeout is a **per-invocation** concern, not executor-global state. A single +executor instance may be shared across agents, tools, and concurrent calls +with different timeout requirements (e.g., a quick validation script vs. a +long-running data analysis). Placing timeout on the executor would create +race conditions when multiple callers set different values. + +```python +@dataclasses.dataclass +class CodeExecutionInput: + code: str + input_files: list[File] = field(default_factory=list) + execution_id: Optional[str] = None + timeout_seconds: Optional[int] = None # NEW + """Maximum execution time in seconds. None means no timeout + (executor default behavior). Each execute_code() call reads + this from its input, not from executor-level state.""" +``` + +Additionally, a **default** timeout on `BaseCodeExecutor` serves as +a fallback when callers don't specify one: + +```python +class BaseCodeExecutor(BaseModel): + default_timeout_seconds: Optional[int] = None + """Default timeout applied when CodeExecutionInput.timeout_seconds + is None. Subclasses may override (e.g., GkeCodeExecutor defaults + to 300). None means no timeout.""" +``` + +The effective timeout is resolved as: +```python +input_t = code_execution_input.timeout_seconds +timeout = ( + input_t if input_t is not None + else self.default_timeout_seconds +) +``` + +**Why per-invocation + executor default:** +- Backward compatible — existing code that doesn't set it works unchanged +- Safe for shared executors — no global mutable state +- Callers can override per-call (e.g., `RunSkillScriptTool` sets + `script_timeout`, LLM flows use a different default) +- Executor subclasses can define their own defaults + +#### 4.2.2 `UnsafeLocalCodeExecutor` — Thread-Based Timeout + +`exec()` cannot be interrupted from the same thread. The solution is to +run it in a separate thread with a join timeout: + +```python +import threading + +def execute_code(self, invocation_context, code_execution_input): + input_t = code_execution_input.timeout_seconds + timeout = ( + input_t if input_t is not None + else self.default_timeout_seconds + ) + if timeout is None: + # No timeout: current behavior (blocking exec) + return self._execute_inline(code_execution_input) + + # Run in a daemon thread with timeout + result_holder = {} + def _run(): + result_holder['result'] = self._execute_inline( + code_execution_input + ) + + thread = threading.Thread(target=_run, daemon=True) + thread.start() + thread.join(timeout=timeout) + + if thread.is_alive(): + # Thread is still running — timeout exceeded. + # Daemon thread will be killed when the process exits. + return CodeExecutionResult( + stderr=f'Execution timed out after {timeout}s' + ) + return result_holder.get('result', CodeExecutionResult( + stderr='Execution produced no result' + )) +``` + +**Trade-offs:** +- Daemon threads cannot be forcefully killed in CPython. If the code enters + a long-running C extension call (e.g., `time.sleep(9999)`), the thread + lingers until process exit. This is acceptable for a local development + executor — production deployments should use container-based executors. +- An alternative is `multiprocessing`, but that adds complexity around + serialization and shared state. + +**Interaction with existing `_execution_lock`:** + +The current `UnsafeLocalCodeExecutor` holds a process-global +`_execution_lock` (`threading.Lock()`) for the entire duration of +`execute_code()`, covering both the sandbox path (temp-dir + chdir) and +the plain path (redirect_stdout only). The timeout thread proposal must +account for this: + +- **Lock must be acquired outside the timeout thread.** The worker thread + must hold the lock while executing, and the calling thread must release + it after the join (whether the worker finishes or times out). If the + lock were acquired inside the worker thread, a timed-out worker would + hold the lock indefinitely, deadlocking all subsequent calls. +- **Recommended pattern — unhealthy guard:** On timeout, the executor + sets `self._healthy = False` before returning the timeout error. The + lock is released normally when the `with` block exits (a `with` + statement always releases on any exit path, including `return`). + The daemon thread may still be running after the lock is released; + the unhealthy flag prevents new executions from starting until the + caller explicitly recovers via `reinitialize()`. + ```python + def execute_code(self, ...): + if not self._healthy: + return CodeExecutionResult( + stderr='Executor unhealthy after timeout. ' + 'Call reinitialize() to recover.' + ) + with _execution_lock: + # Re-check after acquiring the lock: another + # caller may have timed out while we waited. + if not self._healthy: + return CodeExecutionResult( + stderr='Executor unhealthy after ' + 'timeout. Call reinitialize() ' + 'to recover.' + ) + thread = threading.Thread(target=_run, daemon=True) + thread.start() + thread.join(timeout=timeout) + if thread.is_alive(): + self._healthy = False + # Lock released when `with` exits. + # Unhealthy flag blocks future calls. + return CodeExecutionResult( + stderr=f'Execution timed out after ' + f'{timeout}s. Executor marked ' + f'unhealthy.' + ) + ``` +- **Risk:** After the lock is released, the lingering daemon thread + may still be mutating `sys.stdout` or the working directory. The + unhealthy guard ensures no *new* execution races with it, but a + concurrent read of `sys.stdout` from other code could see stale + data. This is an acceptable trade-off for a development executor. +- **Recovery path:** `reinitialize()` joins the lingering daemon + thread with a generous grace timeout (e.g., 30 s). If the thread + exits within the grace period, restore `sys.stdout` and cwd, set + `_healthy = True`, and return success. If the thread is **still + alive** after the grace timeout, the executor remains unhealthy + (`_healthy = False`) and `reinitialize()` raises + `RuntimeError('Timed-out thread did not exit within grace period; + executor remains unhealthy.')`. The caller may retry later or + restart the process. This mirrors the `ContainerCodeExecutor` + recovery model (§4.2.3). + +**Recommendation:** Thread-based timeout with unhealthy guard for +`UnsafeLocalCodeExecutor` is sufficient for a development executor. +Document that timeout triggers an unhealthy state requiring +explicit recovery via `reinitialize()`. + +#### 4.2.3 `ContainerCodeExecutor` — Docker Exec Kill on Timeout + +**Problem with thread+join in containers:** Unlike `UnsafeLocalCodeExecutor` +where a lingering daemon thread is merely wasteful, a runaway process inside +a shared container consumes CPU/memory and can interfere with subsequent +executions. The thread+join pattern would leave the container process +running indefinitely after the join timeout expires. + +**Primary approach: Docker exec kill via `exec_inspect` + PID kill.** + +The key constraint is that `exec_start` is a **blocking** call — a +timer thread cannot unblock it if the in-container kill fails. The +correct design runs `exec_start` in a worker thread so the caller +can enforce the timeout via `thread.join(timeout)`, then uses the +**host-side Docker API** to kill the exec'd process by its host PID. + +```python +import os +import signal +import threading + +def execute_code(self, invocation_context, code_execution_input): + # Fail fast if a prior timeout left the executor unhealthy. + if not self._healthy: + raise RuntimeError( + 'ContainerCodeExecutor is unhealthy after a failed ' + 'timeout cleanup. Call reinitialize() to recover.' + ) + + input_t = code_execution_input.timeout_seconds + timeout = ( + input_t if input_t is not None + else self.default_timeout_seconds + ) + + # Create the exec instance + exec_id = self._client.api.exec_create( + self._container.id, + ['python3', '-c', code_execution_input.code], + )['Id'] + + # Run exec_start in a thread so we can enforce timeout + # from the calling thread. + result_holder = {} + + def _run_exec(): + result_holder['output'] = ( + self._client.api.exec_start(exec_id, demux=True) + ) + + thread = threading.Thread(target=_run_exec, daemon=True) + thread.start() + thread.join(timeout=timeout) + + if thread.is_alive(): + # Timeout exceeded — kill from host side. + # exec_inspect returns the host-namespace PID, which + # is the correct PID for os.kill() on the host. + # (Killing from inside the container would require + # the container-namespace PID, which is different.) + cleanup_failed = False + try: + info = self._client.api.exec_inspect(exec_id) + host_pid = info.get('Pid', 0) + if host_pid > 0: + os.kill(host_pid, signal.SIGKILL) + except ProcessLookupError: + pass # Process already exited — no action needed + except (PermissionError, Exception): + # os.kill failed (most commonly PermissionError + # when container runs as root and ADK does not). + # Restart the container to ensure the runaway + # process is terminated. + try: + self._container.restart(timeout=1) + # Re-validate runtime readiness after restart, + # mirroring the init-time check (see + # container_code_executor.py:169). + check = self._container.exec_run( + ['python3', '--version'] + ) + if check.exit_code != 0: + raise RuntimeError( + f'Post-restart readiness check failed ' + f'(exit_code={check.exit_code})' + ) + except Exception as restart_err: + cleanup_failed = True + logger.error( + 'Timeout cleanup failed: could not kill ' + 'process or restart container: %s', + restart_err, + ) + self._healthy = False + + # Give the worker thread a short window to finish + # after kill/restart, so it doesn't leak indefinitely. + thread.join(timeout=2) + if thread.is_alive(): + logger.warning( + 'Worker thread still alive after timeout ' + 'cleanup; daemon thread will linger until ' + 'process exit.' + ) + + if cleanup_failed: + return CodeExecutionResult( + stderr=( + f'Execution timed out after {timeout}s ' + f'and cleanup failed — executor is ' + f'unhealthy. Reinitialize the executor ' + f'before further use.' + ) + ) + return CodeExecutionResult( + stderr=f'Execution timed out after {timeout}s' + ) + + output = result_holder.get('output') + # ... parse output as before +``` + +**Why this design:** + +1. **`exec_start` in a thread + `join(timeout)`** — The caller is + never blocked longer than `timeout` seconds, regardless of whether + the kill succeeds. This resolves the primary DoS risk. + +2. **Host-side `os.kill(host_pid, SIGKILL)`** — `exec_inspect()` + returns the **host-namespace** PID. Using `os.kill()` from the + host process operates in the host PID namespace, so the PID + matches correctly. This avoids: + - The PID namespace mismatch of killing from inside the container + - The overbroad pattern matching of `pkill -f` (which can hit + concurrent execs or unrelated Python processes) + - Dependency on `procps`/`pkill` being installed in the image + +3. **Post-kill thread join** — After kill/restart, a short + `thread.join(timeout=2)` gives the worker thread time to exit + cleanly. If it's still alive, a warning is logged. The thread is + a daemon, so it will not prevent process exit, but repeated + timeout failures without this join could accumulate leaked threads. + +4. **Unhealthy state on total cleanup failure** — If both `os.kill` + and `container.restart()` fail, the executor sets `self._healthy + = False` and returns a distinct error message. Subsequent calls + check `self._healthy` and raise early rather than queueing work + against a broken container. The `_healthy` lifecycle: + - Initialized to `True` in `__init__` (alongside container start) + - Set to `False` on total cleanup failure (kill + restart both fail) + - Set back to `True` after successful `reinitialize()` (stops + current container, creates new one, passes readiness check) + +5. **Container restart as last resort** — If `os.kill` fails (e.g., + insufficient permissions when Docker runs rootless), restart the + container. This is the most reliable fallback but destroys + in-container state. + +**Permissions and user mismatch risk:** `os.kill()` on the host PID +requires the ADK process to run as the same user that owns the +container's exec'd process on the host. The current +`ContainerCodeExecutor` does not set `user=` on `containers.run()` +(`container_code_executor.py:182`), so the container process runs as +root. If the ADK process runs as a non-root user (common in +development), `os.kill(host_pid, SIGKILL)` will raise +`PermissionError` and the container-restart fallback activates. + +This user mismatch is the expected case for default Docker usage, +so the `PermissionError → container.restart()` path is the **primary +timeout mechanism in practice**, not an edge case. The `os.kill` path +becomes primary only when ADK runs as root or the container is +configured with `user=` matching the host user. + +**Recovery after timeout:** +- **Stateless mode:** No recovery needed. The killed process is gone; + the next `exec_run` starts a fresh process in the same container. +- **Stateful mode (Option A / persistent process):** The timed-out + block is NOT appended to history (append-after-success invariant). + If the persistent REPL was killed or the container was restarted, + the executor returns an error with `stderr` indicating state was + lost. The caller (LLM flow or skill tool) must handle this — + typically by starting a new session. Automatic replay is not + attempted because it may re-execute side effects. + +#### 4.2.4 `GkeCodeExecutor` — Already Implemented + +`GkeCodeExecutor` already has `timeout_seconds: int = 300` applied to the +K8s watch API. Migrate it to use the base class default field: + +```python +class GkeCodeExecutor(BaseCodeExecutor): + default_timeout_seconds: int = 300 # Override base default +``` + +In `execute_code()`, resolve timeout from per-invocation input first: +```python +input_t = code_execution_input.timeout_seconds +timeout = ( + input_t if input_t is not None + else self.default_timeout_seconds +) +``` + +No behavioral change for existing callers (they don't set per-invocation +timeout, so the 300s default applies as before). + +#### 4.2.5 Remote Executors (Vertex AI, Agent Engine) + +These executors delegate to Google Cloud APIs that have their own internal +timeouts. Adding client-side timeout is still valuable as a safety net. + +Note: The current `execute_code()` implementations in +`VertexAiCodeExecutor` and `AgentEngineSandboxCodeExecutor` are +**synchronous** (they call blocking SDK methods), so `asyncio.wait_for()` +is not applicable. Use the same thread+join pattern as +`UnsafeLocalCodeExecutor`: + +- Run the blocking API call in a daemon thread with `join(timeout)` +- Return `CodeExecutionResult(stderr='...')` on timeout +- Log a warning that the server-side execution may still be running +- If these executors are migrated to async in the future, switch to + `asyncio.wait_for()` at that point + +### 4.3 Migration Plan + +| Phase | Action | Risk | +|-------|--------|------| +| 1 | Add `timeout_seconds: Optional[int] = None` to `CodeExecutionInput` | None (backward compatible) | +| 2 | Add `default_timeout_seconds: Optional[int] = None` to `BaseCodeExecutor` | None (backward compatible) | +| 3 | Implement in `UnsafeLocalCodeExecutor` (thread + join) | Low | +| 4 | Implement in `ContainerCodeExecutor` (Docker exec kill) | Low | +| 5 | Migrate `GkeCodeExecutor.timeout_seconds` to `default_timeout_seconds` | None | +| 6 | Add client-side timeout to remote executors | Low | + +### 4.4 Impact on `RunSkillScriptTool` + +Once `BaseCodeExecutor` has native timeout support, the +`RunSkillScriptTool` can optionally delegate timeout enforcement to +the executor rather than embedding it in generated shell wrapper code. +However, the shell wrapper timeout (`subprocess.run(timeout=N)`) should +be kept as defense-in-depth — it catches the subprocess even if the +executor timeout fails. + +**Critical gap — Python scripts have zero timeout protection:** + +Shell scripts benefit from two layers of timeout: the `subprocess.run( +timeout=N)` embedded in generated wrapper code, and (once implemented) +the executor-level timeout. Python scripts have **neither**: + +- `_prepare_code()` generates `runpy.run_path()` inside a plain `exec()` + call — there is no subprocess boundary to kill. +- `SkillToolset.script_timeout` only applies to the shell path (it is + passed to `subprocess.run(timeout=N)`). The docstring explicitly notes: + "Does not apply to Python scripts executed via exec()." +- Until executor-level timeout is implemented, a Python script that hangs + (infinite loop, blocking I/O, deadlock) will block the executor thread + indefinitely. With `UnsafeLocalCodeExecutor`, this also holds the + `_execution_lock`, blocking all other executions. + +**Recommended actions for Phase 1:** +1. Executor-level timeout (§4.2) is the primary fix — it covers both + Python and shell scripts uniformly. +2. As defense-in-depth, `RunSkillScriptTool` should also set + `CodeExecutionInput.timeout_seconds = self._toolset._script_timeout` + once the field is available, ensuring per-invocation timeout even if + the executor has no default. +3. Optionally, the Python wrapper code could be enhanced with a + watchdog thread pattern (similar to the shell `subprocess.run` + timeout), though this is less clean than executor-level enforcement. + +--- + +## 5. Proposal 2: Stateful `ContainerCodeExecutor` + +### 5.1 Problem + +Agents often need multi-step code execution where later steps depend on +earlier results. For example: + +``` +Step 1: import pandas as pd; df = pd.read_csv('data.csv') +Step 2: filtered = df[df['status'] == 'active'] +Step 3: print(filtered.describe()) +``` + +Currently, each `execute_code()` call in `ContainerCodeExecutor` runs +`python3 -c ` — a fresh Python process with no memory of prior +calls. Step 2 would fail with `NameError: name 'df' is not defined`. + +### 5.2 Design + +#### 5.2.1 Architecture + +``` +┌─ ContainerCodeExecutor ─────────────────────┐ +│ │ +│ stateful=False (default): │ +│ exec_run(['python3', '-c', code]) │ +│ └─ Fresh process per call │ +│ │ +│ stateful=True: │ +│ exec_run(['python3', '-c', │ +│ 'exec(open("/app/session.py").read())' │ +│ + '\n' + code │ +│ + '\n_save_state()']) │ +│ └─ Loads prior state, executes, │ +│ saves state back │ +│ │ +└──────────────────────────────────────────────┘ +``` + +**Option A: Persistent Python Process (Complex)** + +Start a long-running Python REPL in the container and pipe code to its +stdin: + +```python +# On init (when stateful=True): +self._exec_id = self._client.api.exec_create( + self._container.id, + ['python3', '-i'], + stdin=True, stdout=True, stderr=True, +) +self._socket = self._client.api.exec_start( + self._exec_id, socket=True +) +``` + +Pros: True statefulness — all Python state (variables, imports, objects) +persists naturally. + +Cons: Complex I/O management. Need to detect when output is "done" for a +given code block (no clean delimiter). Prone to deadlocks. Hard to detect +crashes. + +**Option B: State Serialization via `dill` (Moderate)** + +After each execution, serialize the global namespace to a file in the +container. Before next execution, deserialize it: + +```python +STATEFUL_WRAPPER = ''' +import dill as _dill, os as _os +_state_file = '/tmp/.adk_state.pkl' +if _os.path.exists(_state_file): + _globals = _dill.load(open(_state_file, 'rb')) + globals().update(_globals) + +{user_code} + +# Save state after execution +_save_vars = {k: v for k, v in globals().items() + if not k.startswith('_')} +_dill.dump(_save_vars, open(_state_file, 'wb')) +''' +``` + +Pros: Simpler than persistent REPL. Each call is a clean `exec_run()`. + +Cons: Not all Python objects are serializable (e.g., open file handles, +database connections, generators). Adds `dill` dependency to the container +image. Serialization/deserialization overhead grows with state size. + +**Option C: Shared Globals File (Simple)** + +Write executed code to a cumulative Python file. Each call appends the new +code block and re-executes the entire history: + +```python +HISTORY_FILE = '/tmp/.adk_history.py' + +def execute_code(self, invocation_context, code_execution_input): + if self.stateful: + # Append new code to history + self._container.exec_run( + ['sh', '-c', + f'cat >> {HISTORY_FILE} << "ADKEOF"\n' + f'{code_execution_input.code}\n' + f'ADKEOF'], + ) + # Execute full history + exec_result = self._container.exec_run( + ['python3', HISTORY_FILE], + demux=True, + ) + else: + exec_result = self._container.exec_run( + ['python3', '-c', code_execution_input.code], + demux=True, + ) +``` + +Pros: Simplest approach. No serialization issues. All Python features work. +No new dependencies. + +Cons: Re-executes entire history on each call — side effects run again. +Grows linearly with history length. + +**Mitigation for stdout leakage:** Wrap prior code in a guard: + +```python +# Only new code produces output; prior blocks set up state silently +import sys, io +_old_stdout = sys.stdout +sys.stdout = io.StringIO() +# ... prior code blocks ... +sys.stdout = _old_stdout +# ... new code block (produces output) ... +``` + +**WARNING — Side-effect replay is NOT mitigated by stdout suppression.** +Prior blocks that perform file writes, network calls, database mutations, +or other I/O will re-execute those side effects on every subsequent call. +Stdout suppression only hides `print()` output — it does not prevent or +guard against non-idempotent operations. This is a fundamental limitation +of the cumulative replay approach (Option C). Users must keep +side-effecting code in the final block or use Option A (persistent +process) when side effects are unavoidable. + +#### 5.2.2 Final Target: Option A (Persistent Process) + +**Option A is the final target.** It is the most robust approach for +true statefulness and is the standard design used by Jupyter kernels +and similar systems: + +- Variables, imports, and objects persist naturally +- No re-execution of side effects +- No serialization issues +- O(1) cost per call (not O(n) like Option C) + +Implementation is deferred to **Phase 4** of the roadmap (§8) because +it requires a persistent-process protocol (I/O boundary delimiters, +crash detection, REPL lifecycle management) that is a substantial +design effort on its own. See Open Question 1 (§9) for the protocol +design spike. + +**Acceptance criteria for Option A:** +- Code blocks execute in a long-lived Python REPL process +- Variables, imports, and objects persist across calls +- No replay of prior blocks on each new call +- Crash/OOM triggers automatic REPL restart with clear error +- `execution_id` isolates state across concurrent sessions +- `reset_state()` kills and restarts the REPL + +#### 5.2.3 Interim Fallback: Option C (Cumulative Replay) + +If stateful execution is needed before the persistent-process protocol +is ready, Option C may be shipped as a **time-bounded interim** with +the following restrictions: + +- Documented as limited to **pure computation only** (variable setup, + data transforms, aggregations) +- Side-effecting code (file writes, network calls, DB mutations) is + explicitly unsupported and will produce incorrect results +- Clearly labeled as `experimental` / `unstable` in docstrings and + release notes +- **Deprecation plan:** Option C is removed no later than one minor + release after Option A ships. The `stateful` field docstring must + state: *"Experimental. Uses cumulative replay (Option C). Will be + replaced by persistent-process execution in a future release."* + +#### 5.2.4 Implementation Plan (Option C Interim, if pursued) + +1. **Unfreeze `stateful` in `ContainerCodeExecutor`:** + +```python +# Remove frozen=True +stateful: bool = False +``` + +2. **Add a code history list:** + +```python +_code_history: list[str] = [] +``` + +3. **Modify `execute_code()`:** + +**Critical invariant:** Code is appended to history **only after** +successful execution. A failing code block must never be replayed. + +```python +def execute_code(self, invocation_context, code_execution_input): + code = code_execution_input.code + + if self.stateful: + # Build cumulative script from prior SUCCESSFUL blocks + setup_code = '\n'.join( + f'# --- Block {i} ---\n{block}' + for i, block in enumerate(self._code_history) + ) + # Suppress stdout for prior blocks + full_code = ( + 'import sys as _sys, io as _io\n' + '_sys.stdout = _io.StringIO()\n' + f'{setup_code}\n' + '_sys.stdout = _sys.__stdout__\n' + f'{code}\n' + ) + else: + full_code = code + + exec_result = self._container.exec_run( + ['python3', '-c', full_code], + demux=True, + ) + + # Parse output + stdout, stderr = self._parse_exec_output(exec_result) + success = (exec_result.exit_code == 0) + + # ONLY append to history after confirmed success + if self.stateful and success: + self._code_history.append(code) + + return CodeExecutionResult(stdout=stdout, stderr=stderr) +``` + +4. **Add `reset_state()` method:** + +```python +def reset_state(self): + """Clears the execution history for stateful mode.""" + self._code_history.clear() +``` + +5. **Update the `__init__` validation:** + +```python +# Remove the ValueError for stateful=True +# Keep optimize_data_file frozen +``` + +#### 5.2.5 Interaction with `execution_id` + +The LLM flow layer uses `execution_id` (from `CodeExecutorContext`) to +identify stateful sessions. For `ContainerCodeExecutor`: + +- Each `execution_id` maps to a separate code history +- Use a dict: `_code_histories: dict[str, list[str]] = {}` +- When `execution_id` is provided in `CodeExecutionInput`, use the + corresponding history +- When `execution_id` is `None`, use default (empty) history + +This aligns with how `VertexAiCodeExecutor` uses `session_id`. + +**Gap: `RunSkillScriptTool` does not wire `execution_id`.** + +Currently, `RunSkillScriptTool.run_async()` creates +`CodeExecutionInput(code=..., input_files=..., working_dir='.')` without +setting `execution_id`. +This means all skill script executions share the same (default) namespace +in a stateful executor, with no isolation between different skills or +invocations. + +**Action items:** +1. `RunSkillScriptTool` should generate a **session-stable** + `execution_id` scoped to skill + agent. The key must persist + across turns so that stateful code history is preserved: + ```python + execution_id = f"skill:{skill_name}:{session.id}:{agent_name}" + ``` + Using `invocation_id` would be incorrect here — it changes every + turn, defeating statefulness. `session.id` is stable for the + lifetime of the conversation. +2. Pass `execution_id` to `CodeExecutionInput` +3. This enables future stateful skill scripts where a skill can + maintain state across multiple calls within the same session + +This is tracked as part of the Phase 2 implementation plan. + +### 5.3 Testing Plan + +| Test | Description | +|------|-------------| +| `test_stateful_variable_persistence` | Define variable in call 1, access in call 2 | +| `test_stateful_import_persistence` | Import in call 1, use in call 2 | +| `test_stateful_no_stdout_leakage` | Prior blocks' print() should not appear in later output | +| `test_stateful_error_in_later_block` | Error in call 2 should not corrupt state | +| `test_stateful_reset` | `reset_state()` clears history | +| `test_stateless_unchanged` | Default `stateful=False` behavior unchanged | +| `test_execution_id_isolation` | Different `execution_id` values use separate histories | + +--- + +## 6. Proposal 3: Security Hardening + +### 6.1 Problem + +`UnsafeLocalCodeExecutor` is the default executor for local development +because it requires no external dependencies. But it runs `exec()` in the +host Python process with full access to: + +- The filesystem (read/write any file) +- Environment variables (including API keys, secrets) +- Network (outbound HTTP, DNS) +- The ADK process itself (`os.kill`, `sys.exit`) + +This is a critical security concern when executing: +- LLM-generated code (prompt injection → arbitrary code execution) +- Third-party skill scripts (supply chain risk) +- User-provided code in multi-tenant deployments + +### 6.2 Threat Model + +| Threat | Impact | Current mitigation | +|--------|--------|--------------------| +| LLM generates malicious code | Full host compromise | None | +| Skill script reads secrets | Data exfiltration | None (documented warning only) | +| Infinite loop / fork bomb | DoS / resource exhaustion | Shell: `subprocess.run(timeout=N)` via `script_timeout`; Python: None (no timeout at any layer) | +| `sys.exit()` in script | Process termination | `RunSkillScriptTool` catches `SystemExit`: code 0 or `None` → success; non-zero → `EXECUTION_ERROR` with exit code in message | +| Long error messages | LLM context waste | Exception messages >200 chars truncated to `msg[:200] + "..."` | +| Network exfiltration | Data leak | None | +| File system manipulation | Data loss / corruption | Partial (temp-dir sandbox when `input_files`/`working_dir` set) | + +### 6.3 Design + +We propose a layered approach with three tiers of security: + +#### 6.3.1 Tier 1: `UnsafeLocalCodeExecutor` Hardening (Quick Wins) + +These changes improve safety without changing the fundamental architecture: + +**A. Timeout support** (covered in Proposal 1) + +**B. Restricted builtins (best-effort friction, NOT a security boundary):** + +**Important caveat:** Builtin/module blocking in `exec()` is trivially +bypassed. Determined code can reach blocked functionality via: +- `object.__subclasses__()` → find `os._wrap_close` → access `os.system` +- `__builtins__.__dict__['__import__']('os')` (if `__builtins__` is a + module, not a dict) +- Encoding tricks, `importlib` via `sys.modules`, etc. + +This is explicitly **not a security control** — it is a speed bump that +catches accidental misuse and makes intentional abuse more visible. True +isolation requires `LocalSandboxCodeExecutor` (Tier 2) or containers +(Tier 3). + +```python +_BLOCKED_BUILTINS = { + 'exec', 'eval', 'compile', # Prevent meta-execution + '__import__', # Prevent arbitrary imports + 'open', # Prevent file access + 'breakpoint', # Prevent debugger attach +} + +_BLOCKED_MODULES = { + 'os', 'subprocess', 'shutil', # System access + 'socket', 'http', 'urllib', # Network access + 'ctypes', 'cffi', # Native code + 'importlib', # Dynamic imports +} +``` + +**Trade-off:** This breaks legitimate use cases (e.g., data analysis scripts +that need `open()` for file I/O). It should be opt-in: + +```python +class UnsafeLocalCodeExecutor(BaseCodeExecutor): + restrict_builtins: bool = False + """When True, block dangerous builtins (exec, eval, open, + __import__). This is a best-effort friction layer, NOT a + security boundary — determined code can bypass it. Use + LocalSandboxCodeExecutor or ContainerCodeExecutor for + actual isolation. Default False for backward compatibility.""" +``` + +**C. Warning on first use:** + +```python +import warnings + +def execute_code(self, ...): + if not self._warned: + warnings.warn( + 'UnsafeLocalCodeExecutor runs code in the host ' + 'process with NO isolation. Use ' + 'ContainerCodeExecutor or GkeCodeExecutor for ' + 'production deployments.', + SecurityWarning, + stacklevel=2, + ) + self._warned = True + ... +``` + +#### 6.3.2 Tier 2: `LocalSandboxCodeExecutor` (New, Recommended) + +A new executor that provides meaningful isolation without requiring Docker +or cloud services: + +**Approach: `subprocess` with resource limits** + +```python +class LocalSandboxCodeExecutor(BaseCodeExecutor): + """Executes Python code in a sandboxed subprocess. + + Provides isolation via: + - Separate process (no shared memory with host) + - Resource limits via ulimit (CPU time, memory) + - Restricted environment variables + - Optional chroot or tmpdir working directory + """ + + default_timeout_seconds: int = 30 + max_memory_mb: int = 256 + max_cpu_seconds: int = 30 + allowed_env_vars: list[str] = [] + + def execute_code(self, invocation_context, code_execution_input): + import os + import platform + import signal + import subprocess + import sys + import tempfile + + # Windows is out of scope (§2 Non-Goals). + if platform.system() == 'Windows': + raise NotImplementedError( + 'LocalSandboxCodeExecutor is not supported on ' + 'Windows. Use ContainerCodeExecutor instead.' + ) + + with tempfile.TemporaryDirectory() as temp_dir: + # Materialize input_files into the temp directory, + # preserving relative paths (mirrors + # UnsafeLocalCodeExecutor sandbox behavior). + for f in (code_execution_input.input_files or []): + file_path = os.path.join( + temp_dir, f.path or f.name + ) + os.makedirs( + os.path.dirname(file_path), exist_ok=True + ) + mode = 'wb' if isinstance(f.content, bytes) \ + else 'w' + with open(file_path, mode) as out_f: + out_f.write(f.content) + + # Honor working_dir: resolve as subdirectory of + # temp_dir (same contract as + # UnsafeLocalCodeExecutor). + if code_execution_input.working_dir: + exec_dir = os.path.join( + temp_dir, + code_execution_input.working_dir, + ) + os.makedirs(exec_dir, exist_ok=True) + else: + exec_dir = temp_dir + + # Write code to a temp file inside exec_dir + script_path = os.path.join(exec_dir, '_run.py') + with open(script_path, 'w') as sf: + sf.write(code_execution_input.code) + + # Build restricted environment + env = { + k: os.environ[k] + for k in self.allowed_env_vars + if k in os.environ + } + env['PATH'] = '/usr/bin:/usr/local/bin' + + input_t = code_execution_input.timeout_seconds + timeout = ( + input_t if input_t is not None + else self.default_timeout_seconds + ) + if timeout is None: + timeout = self.max_cpu_seconds + + # Prefer process_group (3.11+) over preexec_fn + # (not fork-safe with threads). + spawn_kwargs = {} + if sys.version_info >= (3, 11): + spawn_kwargs['process_group'] = 0 + else: + # Fallback for 3.10; caveat: preexec_fn is not + # fork-safe in multi-threaded programs. + # Must call os.setpgrp() so os.killpg() works + # on timeout, AND set resource limits. + def _setup_child(): + os.setpgrp() # new process group + try: + import resource + resource.setrlimit( + resource.RLIMIT_CPU, + (self.max_cpu_seconds,) * 2, + ) + mem = self.max_memory_mb * 1024 * 1024 + resource.setrlimit( + resource.RLIMIT_AS, (mem, mem), + ) + except (ImportError, OSError): + pass # timeout-only enforcement + spawn_kwargs['preexec_fn'] = _setup_child + + # Inline wrapper sets resource limits in the child + # process. Guarded for missing resource module. + limit_code = ( + f'try:\n' + f' import resource\n' + f' resource.setrlimit(resource.RLIMIT_CPU, ' + f'({self.max_cpu_seconds}, ' + f'{self.max_cpu_seconds}))\n' + f' resource.setrlimit(resource.RLIMIT_AS, ' + f'({self.max_memory_mb * 1024 * 1024}, ' + f'{self.max_memory_mb * 1024 * 1024}))\n' + f'except (ImportError, OSError):\n' + f' pass\n' + ) + cmd = [ + 'python3', '-c', + limit_code + + f'exec(open({script_path!r}).read())', + ] + + # Use Popen for explicit process-group kill on + # timeout (subprocess.run only kills the direct + # child, leaving descendants alive). + try: + proc = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=env, + cwd=exec_dir, + **spawn_kwargs, + ) + stdout, stderr = proc.communicate( + timeout=timeout, + ) + except subprocess.TimeoutExpired: + # Kill the entire process group to reap + # descendants (fork bombs, child workers). + try: + os.killpg(proc.pid, signal.SIGKILL) + except OSError: + proc.kill() # fallback + proc.wait() + return CodeExecutionResult( + stdout='', + stderr=( + f'Execution timed out after ' + f'{timeout}s' + ), + ) + + return CodeExecutionResult( + stdout=stdout, + stderr=stderr if proc.returncode != 0 + else '', + ) +``` + +**Platform considerations:** +- `resource.setrlimit` is Unix-only (Linux, macOS). On platforms + where `resource` is unavailable, the inline `-c` wrapper must + skip the `setrlimit` calls and rely on timeout-only enforcement. + The code should guard with `try: import resource; ... except + ImportError: pass` in the wrapper script. +- `process_group=0` requires Python 3.11+ (ADK supports >=3.10, so + this must be gated with a version check or use `preexec_fn` as + fallback on 3.10) +- Windows is out of scope (see §2 Non-Goals). The executor should + raise `NotImplementedError` on Windows with a message directing + users to `ContainerCodeExecutor`. + +**Why `process_group` instead of `preexec_fn`:** +- `preexec_fn` is not fork-safe with threads — the Python docs warn + that it can deadlock in multi-threaded programs because it runs + between `fork()` and `exec()` while all parent thread locks are + held. ADK executors may be called from async/threaded contexts. +- `process_group=0` (Python 3.11+) is fork-safe and places the child + in its own process group, enabling clean `os.killpg()` on timeout. +- On Python 3.11+, resource limits are set via an inline `-c` + wrapper script (not `preexec_fn`), avoiding the fork-safety issue. +- On Python 3.10 (ADK minimum is `>=3.10`), fall back to + `preexec_fn=_setup_child` which calls `os.setpgrp()` (required + for `os.killpg` on timeout) **and** sets `resource.setrlimit` + for CPU/memory. The inline `-c` wrapper still applies limits as + a defense-in-depth layer. Documented caveat: `preexec_fn` is not + fork-safe in multi-threaded programs. + +**Dependencies:** None (stdlib only). This is the key advantage over +`ContainerCodeExecutor`. + +**Limitations:** +- Less isolation than containers (shared filesystem, kernel) +- Cannot restrict network access without OS-level firewall rules +- `process_group` requires Python 3.11+; falls back to `preexec_fn` + on 3.10 (ADK minimum is `>=3.10` per `pyproject.toml`) + +#### 6.3.3 Tier 3: Promote `ContainerCodeExecutor` as Default + +For production deployments, container-based isolation should be the +standard recommendation: + +**A. Simplify setup with digest-pinned default image:** + +```python +# Current: requires explicit image or docker_path +executor = ContainerCodeExecutor(image='python:3.11-slim') + +# Proposed: auto-pull default image (digest-pinned) +executor = ContainerCodeExecutor() +``` + +**Default image should use a digest-pinned or versioned tag**, not a +mutable tag like `python:3.11-slim`. Mutable tags can change content +silently (e.g., security patches, Python micro-version bumps), leading +to non-reproducible behavior across environments and over time. + +```python +# In ContainerCodeExecutor defaults: +_DEFAULT_IMAGE = ( + 'python:3.11.11-slim@sha256:' +) +# Updated in ADK releases with tested digests +``` + +When an official `adk-code-executor` image is published, the default +should reference a versioned tag matching the ADK release: +```python +_DEFAULT_IMAGE = 'gcr.io/adk/code-executor:0.5.0' +``` + +**B. Pre-built ADK executor image:** + +Create an official `adk-code-executor` Docker image with: +- Python 3.11+ slim base (digest-pinned in Dockerfile) +- Common data science libraries (pandas, numpy, matplotlib) +- Non-root user +- Read-only filesystem (writable `/tmp` only) +- No network access by default (`--network=none`) +- Versioned tags matching ADK releases + +```dockerfile +FROM python:3.11.11-slim@sha256: +RUN pip install --no-cache-dir pandas numpy matplotlib +RUN useradd -m -s /bin/bash executor +USER executor +WORKDIR /home/executor +``` + +**C. Network isolation (opt-in, graduating to default):** + +These hardening options **break scripts that require network access or +write outside `/tmp`**. They are introduced as explicit opt-in flags +first, then graduated to defaults in a later minor release with a +deprecation warning cycle. + +**Phase 3 (initial release) — opt-in:** + +```python +class ContainerCodeExecutor(BaseCodeExecutor): + # New opt-in fields (default False to preserve + # backward compatibility). + disable_network: bool = False + read_only_rootfs: bool = False + mem_limit: Optional[str] = None # e.g. '512m' + cpu_quota: Optional[int] = None # e.g. 50000 + +def __init_container(self): + run_kwargs = dict( + image=self.image, + detach=True, + tty=True, + ) + if self.disable_network: + run_kwargs['network_mode'] = 'none' + if self.read_only_rootfs: + run_kwargs['read_only'] = True + run_kwargs['tmpfs'] = {'/tmp': 'size=100M'} + if self.mem_limit: + run_kwargs['mem_limit'] = self.mem_limit + if self.cpu_quota: + run_kwargs['cpu_period'] = 100000 + run_kwargs['cpu_quota'] = self.cpu_quota + self._container = self._client.containers.run( + **run_kwargs + ) +``` + +**Future release — graduate to default:** + +Flipping `disable_network` and `read_only_rootfs` from `False` to +`True` is a **breaking behavior change** under SemVer (existing code +that relies on network access or host-filesystem writes will fail). +The graduation plan must follow ADK's SemVer policy: + +- **Option A (minor release, preferred if ADK is pre-1.0):** Pre-1.0 + SemVer permits breaking changes in minor releases. Emit a + `DeprecationWarning` for at least one minor release before the + flip. Users who need the old behavior set explicit `False`. +- **Option B (post-1.0):** Reserve the default flip for a **major** + release. In the preceding minor release(s), emit a + `DeprecationWarning` when these flags are unset, warning that the + default will change in the next major version. + +Either way, the deprecation warning must state the exact version +where the default changes and the explicit opt-out syntax. + +### 6.4 Recommendation Matrix + +| Use Case | Recommended Executor | Why | +|----------|---------------------|-----| +| Local development | `LocalSandboxCodeExecutor` | No deps, basic isolation | +| Quick prototyping | `UnsafeLocalCodeExecutor` | Fastest setup, no isolation | +| CI/CD testing | `ContainerCodeExecutor` | Docker available in CI | +| Production (single tenant) | `ContainerCodeExecutor` | Good isolation, local | +| Production (multi-tenant) | `GkeCodeExecutor` | gVisor, per-execution isolation | +| Google Cloud | `AgentEngineSandboxCodeExecutor` | Managed, scalable | + +### 6.5 Implementation Plan + +| Phase | Action | Effort | Risk | +|-------|--------|--------|------| +| 1 | Add `SecurityWarning` to `UnsafeLocalCodeExecutor` | Small | None | +| 2 | Add `restrict_builtins` option | Small | Low | +| 3 | Implement `LocalSandboxCodeExecutor` | Medium | Low | +| 4 | Add default image + network/rootfs isolation as **opt-in** flags | Medium | Low | +| 5 | Create official `adk-code-executor` Docker image | Medium | Low | +| 6 | Update documentation and samples | Small | None | +| 7 | Graduate network/rootfs isolation to **default** (future release: minor pre-1.0 / major post-1.0; see §6.3.3-C) | Small | Medium (breaking for scripts needing network/host writes) | + +--- + +## 7. Cross-Cutting Concerns + +### 7.1 `BaseCodeExecutor` API Changes + +All three proposals touch `BaseCodeExecutor`. The combined changes: + +```python +class BaseCodeExecutor(BaseModel): + # Existing fields (unchanged) + optimize_data_file: bool = False + stateful: bool = False + error_retry_attempts: int = 2 + code_block_delimiters: List[tuple[str, str]] = [ + ('```tool_code\n', '\n```'), + ('```python\n', '\n```'), + ] + execution_result_delimiters: tuple[str, str] = ( + '```tool_output\n', '\n```' + ) + + # NEW: Proposal 1 + default_timeout_seconds: Optional[int] = None + """Default timeout applied when CodeExecutionInput.timeout_seconds + is None. Subclasses may override. None = no timeout.""" + + @abc.abstractmethod + def execute_code( + self, + invocation_context: InvocationContext, + code_execution_input: CodeExecutionInput, + ) -> CodeExecutionResult: ... + + +@dataclasses.dataclass +class CodeExecutionInput: + code: str + input_files: list[File] = field(default_factory=list) + execution_id: Optional[str] = None + working_dir: Optional[str] = None + timeout_seconds: Optional[int] = None # NEW: per-invocation + """Per-invocation timeout. Overrides executor default when set.""" +``` + +### 7.2 Backward Compatibility + +| Change | Backward compatible? | Migration needed? | +|--------|---------------------|------------------| +| `default_timeout_seconds` on base class | Yes (default `None`) | No | +| `timeout_seconds` on `CodeExecutionInput` | Yes (default `None`) | No | +| Unfreeze `stateful` on `ContainerCodeExecutor` | Yes (default `False`) | No | +| `SecurityWarning` on `UnsafeLocalCodeExecutor` | Yes (warning only) | No | +| New `LocalSandboxCodeExecutor` | Yes (additive) | No | +| `restrict_builtins` on `UnsafeLocalCodeExecutor` | Yes (default `False`) | No | +| Default image for `ContainerCodeExecutor` | Breaking behavior change (currently requires explicit `image` or `docker_path`; adding a default changes what runs). Pre-1.0: may ship in a minor release with one-cycle `DeprecationWarning`. Post-1.0: reserve for a major release per SemVer. | Emit `DeprecationWarning` when no image specified; docs must show explicit `image=` in all examples during transition. | + +### 7.3 Impact on `RunSkillScriptTool` + +| Feature | Current workaround | After enhancements | +|---------|-------------------|-------------------| +| Shell timeout | Embedded `subprocess.run(timeout=N)` via `SkillToolset.script_timeout` (default 300s) | Keep as defense-in-depth + executor-level timeout | +| Python timeout | **None** — `runpy.run_path()` runs inline in `exec()` with no timeout at any layer | Executor-level timeout handles it; tool should also set `CodeExecutionInput.timeout_seconds` | +| Isolation | Partial temp-dir sandbox (input_files/working_dir) + `_execution_lock` for stdout/cwd; no restriction on filesystem/network/env access | `LocalSandboxCodeExecutor` or container | +| Stateful scripts | Not supported (`execution_id` not wired) | Available via `ContainerCodeExecutor(stateful=True)` with `execution_id` | +| Output files | `CodeExecutionResult.output_files` silently dropped | Surfaced in tool response (§7.5.2) | +| System instructions | `SkillToolset.process_llm_request()` injects `DEFAULT_SKILL_SYSTEM_INSTRUCTION` + XML skill list | No change needed | +| Error truncation | Exception messages >200 chars truncated | Consider making threshold configurable | + +### 7.4 Testing Strategy + +**Current test coverage gaps:** Unit tests exist for +`UnsafeLocalCodeExecutor`, `GkeCodeExecutor`, +`AgentEngineSandboxCodeExecutor`, `BuiltInCodeExecutor`, and +`CodeExecutorContext`, but **no unit test file exists for +`ContainerCodeExecutor`** (`tests/unittests/code_executors/` has no +`test_container_code_executor.py`). Likewise, `LocalSandboxCodeExecutor` +is new and has no tests yet. + +| Category | Approach | New tests needed | +|----------|----------|-----------------| +| Unit tests | Mock-based tests per executor | **Add `test_container_code_executor.py`**, add `test_local_sandbox_code_executor.py` | +| Integration tests | Real executor tests (like `RunSkillScriptTool` integration tests) | Add Docker-based container tests (CI-gated) | +| Timeout tests | Scripts with `time.sleep()` to verify enforcement | Per-executor timeout tests | +| Timeout kill fallback | Verify `PermissionError` from `os.kill` triggers container restart | Mock `os.kill` to raise `PermissionError`, assert `container.restart()` called and `CodeExecutionResult.stderr` contains timeout message | +| Timeout kill success | Verify `os.kill(host_pid)` path when permitted | Mock `exec_inspect` to return PID, assert `os.kill` called with correct signal | +| Timeout total failure | Verify both `os.kill` and `container.restart()` fail → unhealthy | Mock both to raise, assert `_healthy` is `False` and `stderr` contains "cleanup failed" | +| Timeout thread leak | Verify post-kill `join(2)` is called and warning logged if thread lingers | Mock thread to stay alive after kill, assert warning logged | +| Security tests | Scripts attempting blocked operations | `restrict_builtins` bypass attempts, env var leakage | +| Stateful tests | Multi-call sequences verifying variable persistence | Append-after-success, failure-does-not-poison, `execution_id` isolation | +| Stateful crash recovery | Verify error returned on REPL/container crash | Kill REPL mid-execution, assert error indicates state loss | +| Tool contract tests | Validate structured `RunSkillScriptTool` response schema | Assert `return_code`, `timed_out`, `status`, and error envelope consistency | +| Output propagation tests | Verify executor `output_files` are surfaced by tool | Assert tool response includes generated files/metadata | +| Args normalization tests | Verify deterministic mapping from JSON args to argv | Cover booleans, lists, positional args, and invalid types | +| `execution_id` wiring tests | Verify stable and scoped `execution_id` generation | Assert per-session/per-skill isolation and persistence semantics | + +### 7.5 High-Priority `RunSkillScriptTool` Contract Enhancements + +These improvements are additive and can be shipped before stateful container +support. + +#### 7.5.1 Structured Execution Result Schema + +Current output is largely free-form (`stdout`, `stderr`, derived `status`). +Add explicit structured fields: + +```python +{ + "skill_name": "...", + "script_path": "...", + "status": "success|warning|error", + "return_code": int | None, + "timed_out": bool, + "stdout": str, + "stderr": str, + "output_files": [...], # see §7.5.2 +} +``` + +Guidance: +- `status` should be derived from structured fields (`return_code`, + `timed_out`, and stream presence), not treated as the source of truth. +- Tool-level validation/configuration errors should continue using explicit + `error_code` values. + +**Current status derivation and its asymmetry:** + +The current implementation determines status purely from stream presence: +```python +if stderr and not stdout: + status = "error" +elif stderr: + status = "warning" +else: + status = "success" +``` + +This creates an asymmetry between script types: + +- **Shell scripts:** Non-zero `returncode` from the JSON envelope causes + synthesized stderr (`"Exit code {rc}"`), so return codes **indirectly** + influence status. A shell script that fails silently (non-zero exit but + no stderr) still gets `"error"` status. +- **Python scripts:** There is **no return code extraction**. A Python + script that exits cleanly but writes warnings to stderr (common in + data science libraries) would be classified as `"error"` or `"warning"` + even if it succeeded. Conversely, a Python script that silently produces + incorrect output would get `"success"` status. + +The proposed `return_code` field resolves this by providing a uniform +source of truth. For Python scripts, this would require either: +(a) wrapping the `runpy.run_path()` call to capture the exit code, or +(b) treating any non-exception completion as `return_code = 0`. + +#### 7.5.2 Propagate `output_files` and Artifact Metadata + +`CodeExecutionResult.output_files` should be surfaced in the tool response. +This is critical for scripts that generate reports, transformed datasets, or +intermediate artifacts. + +Minimum expected shape: + +```python +output_files = [ + { + "name": str, + "mime_type": str | None, + # optional future fields: + # "artifact_id": str, + # "path": str, + } +] +``` + +#### 7.5.3 `execution_id` Wiring in `RunSkillScriptTool` + +Even before full stateful container support, wire a deterministic +`execution_id` to avoid ambiguous namespaces in stateful-capable executors. + +Recommended key shape: + +```python +execution_id = ( + f"skill:{skill_name}:session:{session_id}:agent:{agent_name}" +) +``` + +Rules: +- Stable across turns within the same session. +- Scoped by skill and agent. +- Never derived from `invocation_id` (too short-lived). + +#### 7.5.4 Script Args Normalization Contract + +**Current behavior:** The implementation uses a simple `str(v)` conversion +for all argument values, with no type-aware normalization: + +```python +# Both Python and shell paths use the same logic: +for k, v in script_args.items(): + argv_list.extend([f"--{k}", str(v)]) +``` + +This means: +- `{"verbose": true}` → `["--verbose", "True"]` (string, not a flag) +- `{"flag": false}` → `["--flag", "False"]` (not omitted) +- `{"items": [1, 2, 3]}` → `["--items", "[1, 2, 3]"]` (repr of list) +- `{"count": 42}` → `["--count", "42"]` (correct) +- Nested objects → `["--config", "{'a': 1}"]` (repr, not useful) + +Additionally, `args` type is validated to be a `dict` — non-dict values +(strings, lists, integers, booleans) return `INVALID_ARGS_TYPE` error. + +**Proposed rules** (define deterministic mapping from JSON args to argv): +- `str|int|float` -> `--key value` +- `true` -> `--key` (flag only, no value) +- `false|None` -> omit entirely +- `list[...]` -> repeated `--key value` entries +- Optional reserved key for positional args (for example, `_positional`) +- Reject nested objects with explicit validation error + +This reduces LLM-side ambiguity and improves replay/debug stability. + +**Migration note:** Changing boolean handling from `"--key True"` to +`"--key"` (flag) is a behavioral change. Existing skill scripts that +parse `--verbose True` as a string value would break. The migration +should be opt-in or gated behind a version flag. + +--- + +## 8. Implementation Roadmap + +### 8.1 Priority-Ordered Plan + +#### Phase 1 (P0): Timeout Foundation (3-4 days) + +1. Add `timeout_seconds: Optional[int] = None` to `CodeExecutionInput` +2. Add `default_timeout_seconds: Optional[int] = None` to + `BaseCodeExecutor` +3. Implement thread-based timeout in `UnsafeLocalCodeExecutor` +4. Implement Docker exec kill timeout in `ContainerCodeExecutor` + (including `_healthy` guard, post-restart readiness validation, + and post-kill thread join) +5. Add public `reinitialize()` method to `ContainerCodeExecutor`: + stops the current container (if any), creates a new one, runs + readiness check, and sets `_healthy = True`. This is the + documented recovery path when `_healthy` is `False`. Callable + by users or by higher-level retry logic. +6. Migrate `GkeCodeExecutor.timeout_seconds` to `default_timeout_seconds` +7. Add timeout tests for each executor +8. Update `RunSkillScriptTool` to set per-invocation timeout via + `CodeExecutionInput.timeout_seconds` + +#### Phase 2 (P1): `RunSkillScriptTool` Contract Hardening (2-3 days) + +1. Add structured response fields: `return_code`, `timed_out`, + schema-stable status semantics +2. Surface executor `output_files` in tool output +3. Define and implement args normalization contract +4. Add deterministic `execution_id` wiring for tool calls +5. Add tool-level contract tests (schema, args, output propagation, + `execution_id` isolation behavior) + +#### Phase 3 (P0): Security Hardening (5-7 days) + +1. Add `SecurityWarning` to `UnsafeLocalCodeExecutor` +2. Add `restrict_builtins` option (documented as best-effort friction) +3. Implement `LocalSandboxCodeExecutor` (using `process_group`, not + `preexec_fn`) +4. Add digest-pinned default image to `ContainerCodeExecutor` +5. Add network/rootfs isolation as **opt-in** flags on + `ContainerCodeExecutor` (`disable_network`, `read_only_rootfs`, + both default `False`; see §6.3.3-C for graduation plan) +6. Create official `adk-code-executor` Docker image (versioned tags) +7. Update all samples to recommend secure executors +8. Add security-focused tests + +#### Phase 4 (P2): Stateful Container (5-8 days) + +Implement Option A (persistent process) directly, as recommended in +§5.2.2. This avoids the side-effect replay problems of Option C. + +1. Unfreeze `stateful` on `ContainerCodeExecutor` +2. Design persistent-process protocol: sentinel-delimited I/O for + output boundaries, error detection, and process health checks +3. Implement persistent Python REPL management (start, send code, + read output, detect crash/restart) +4. Add `execution_id`-based session isolation (one REPL per + `execution_id`; wiring in `RunSkillScriptTool` is done in + Phase 2 — see §5.2.5) +5. Add `reset_state()` method (kills and restarts the REPL) +6. Add stateful execution tests (variable persistence, crash recovery, + `execution_id` isolation) +7. Update samples and documentation + +### Total estimated effort: 15-22 days + +> **Scope note:** This covers all four phases (P0 timeout + P0 security +> + P1 contract hardening + P2 stateful container). The companion RFC +> (`rfc_runskillscript_p0.md`) scopes only P0-A (timeout) and P0-B +> (LocalSandboxCodeExecutor), estimated at 8-11 days. + +--- + +## 9. Open Questions + +1. **What I/O boundary protocol should the persistent REPL use?** + The roadmap targets Option A (persistent process) directly. The + key design question is how to delimit output for each code block: + sentinel strings in stdout, JSON-envelope protocol, or a side + channel (e.g., file-based result). Sentinel strings are simplest + but can collide with user output. Decision: spike during Phase 4 + (Stateful Container, §8). + +2. **Should `LocalSandboxCodeExecutor` support stateful execution?** + Subprocess-based execution is inherently stateless. Stateful support + would require the same workarounds as `ContainerCodeExecutor` (Option + C). We recommend keeping it stateless in the initial implementation. + +3. **Should we deprecate `UnsafeLocalCodeExecutor`?** + Not immediately. It's useful for zero-dependency development. But the + `SecurityWarning` and documentation should steer users toward safer + alternatives for anything beyond local prototyping. + +4. **How should `ContainerCodeExecutor` handle container/REPL crashes + in stateful mode?** + If the container crashes (OOM, segfault) or the persistent REPL + dies, in-process state is lost. The executor returns an error + indicating state loss and lets the caller handle recovery (e.g., + start a new session). Automatic replay is not attempted because + prior code blocks may have had side effects that should not be + re-executed (consistent with §4.2.3 recovery policy). + +--- + +## 10. References + +- [BaseCodeExecutor](../../src/google/adk/code_executors/base_code_executor.py) +- [ContainerCodeExecutor](../../src/google/adk/code_executors/container_code_executor.py) +- [UnsafeLocalCodeExecutor](../../src/google/adk/code_executors/unsafe_local_code_executor.py) +- [GkeCodeExecutor](../../src/google/adk/code_executors/gke_code_executor.py) +- [VertexAiCodeExecutor](../../src/google/adk/code_executors/vertex_ai_code_executor.py) +- [AgentEngineSandboxCodeExecutor](../../src/google/adk/code_executors/agent_engine_sandbox_code_executor.py) +- [RunSkillScriptTool](../../src/google/adk/tools/skill_toolset.py) +- [Code Execution Flow](../../src/google/adk/flows/llm_flows/_code_execution.py) +- [PR #4575 — RunSkillScriptTool](https://github.com/google/adk-python/pull/4575) diff --git a/docs/design/rfc_runskillscript_p0.md b/docs/design/rfc_runskillscript_p0.md new file mode 100644 index 0000000000..593d402b9e --- /dev/null +++ b/docs/design/rfc_runskillscript_p0.md @@ -0,0 +1,532 @@ +# RFC: Production-Readiness for RunSkillScriptTool + +**Authors:** haiyuancao +**Date:** 2026-02-24 +**Status:** Proposed +**Audience:** ADK TL / UTL +**Effort:** 8-11 engineering days (P0 scope only; see + `code_executor_enhancements.md` for full 15-22 day estimate + covering P0-P2) +**Tracking:** Follow-up to PR #4575 (RunSkillScriptTool) + +--- + +## 1. Executive Summary + +`RunSkillScriptTool` lets agents execute Python and shell scripts +bundled with skills. It shipped in PR #4575 and is functional, but two +gaps block production use: + +1. **Python scripts can hang forever.** Shell scripts have a + `subprocess.run(timeout=300)` guard; Python scripts have none. A + single stuck `runpy.run_path()` call holds a process-global lock, + blocking every subsequent execution across all agents in the process. + +2. **All local execution is unprotected.** `UnsafeLocalCodeExecutor` — + the only zero-dependency executor and the default for development — + runs `exec()` in the host process. A malicious or buggy script can + read secrets, write to the filesystem, exfiltrate data over the + network, or crash the process. + +This RFC proposes two changes, scoped to what is required before skills +can be used in any environment beyond local prototyping: + +- **P0-A: Uniform timeout** — Add `timeout_seconds` to the executor + contract so every `execute_code()` call has a bounded lifetime. +- **P0-B: `LocalSandboxCodeExecutor`** — A new stdlib-only executor + that runs code in a subprocess with resource limits, replacing + `UnsafeLocalCodeExecutor` as the recommended local default. + +Both changes are backward-compatible, additive, and independently +shippable. + +--- + +## 2. Problem Statement + +### 2.1 The Timeout Gap + +The executor landscape today: + +| Executor | Timeout | How | +|----------|---------|-----| +| `UnsafeLocalCodeExecutor` | **None** | `exec()` blocks forever | +| `ContainerCodeExecutor` | **None** | `exec_run()` blocks forever | +| `GkeCodeExecutor` | 300 s | K8s watch API | +| `VertexAiCodeExecutor` | Opaque | Vertex AI internal | +| `AgentEngineSandboxCodeExecutor` | Opaque | Vertex AI Sandbox internal | + +`RunSkillScriptTool` works around this for shell scripts by embedding +`subprocess.run(timeout=N)` in generated wrapper code. The default is +300 seconds, configurable via `SkillToolset(script_timeout=N)`. + +**Python scripts have zero timeout at any layer.** The tool generates: + +```python +import sys, runpy +sys.argv = ['scripts/run.py', '--verbose', 'True'] +runpy.run_path('scripts/run.py', run_name='__main__') +``` + +This runs inline inside `exec()`. There is no subprocess boundary, no +watchdog thread, and no way for the caller to interrupt it. Worse, +`UnsafeLocalCodeExecutor` holds a process-global `threading.Lock()` +for the entire execution (required because `redirect_stdout` and +`os.chdir` mutate process-global state). A hung Python script +deadlocks the lock, blocking **all** code execution across the entire +process — every agent and every `UnsafeLocalCodeExecutor` instance +shares the same module-level `_execution_lock`. + +**Impact:** A single infinite-loop in a skill script takes down the +entire ADK process. This is a denial-of-service risk for any +deployment — not just production, but also development servers and +demos. + +### 2.2 The Security Gap + +`UnsafeLocalCodeExecutor` runs code with the full privileges of the +host Python process: + +| Threat | Impact | Current Mitigation | +|--------|--------|--------------------| +| Read env vars / secrets | Data exfiltration | None | +| Write to host filesystem | Data loss / corruption | Partial (temp-dir sandbox when `input_files` or `working_dir` is set) | +| Outbound network calls | Data leak | None | +| `sys.exit()` | Process crash | `SystemExit` caught in tool | +| Infinite loop / fork bomb | DoS | Shell: `subprocess.run(timeout)`; Python: **none** | + +This executor is the only one that requires zero external dependencies. +While `LlmAgent.code_executor` does not globally default to it (it +defaults to `None`, and CFC paths may force `BuiltInCodeExecutor`), +`UnsafeLocalCodeExecutor` is the common choice in practice for setups +that need local code execution: +- Samples and tutorials that demonstrate `code_executor=` configuration +- `adk web` / `adk run` development workflows +- CI test suites without Docker + +Any code the LLM generates or any third-party skill script runs with +full host access. This is acceptable for trusted, single-developer +prototyping. It is not acceptable for: +- Multi-user development servers +- CI/CD pipelines running untrusted skill scripts +- Any path toward production deployment + +--- + +## 3. Proposed Solution + +### 3.1 P0-A: Uniform Timeout Support + +**Goal:** Every `execute_code()` call has a bounded lifetime, regardless +of executor backend or script type. + +#### 3.1.1 Contract Changes (Backward-Compatible) + +Add one field to each layer: + +```python +# Per-invocation timeout (caller sets this) +@dataclasses.dataclass +class CodeExecutionInput: + code: str + input_files: list[File] = field(default_factory=list) + execution_id: Optional[str] = None + working_dir: Optional[str] = None + timeout_seconds: Optional[int] = None # NEW + +# Executor-level default (fallback when caller doesn't set one) +class BaseCodeExecutor(BaseModel): + default_timeout_seconds: Optional[int] = None # NEW + ... +``` + +Resolution logic in every executor: +```python +timeout = ( + code_execution_input.timeout_seconds + if code_execution_input.timeout_seconds is not None + else self.default_timeout_seconds +) +``` + +**Why two fields, not one?** +- A single executor instance may be shared across agents/tools with + different timeout needs (quick validation vs. long data analysis). +- Per-invocation is the source of truth; executor default is the + safety net for callers that don't set one. +- Existing code that sets neither field gets `None` → no timeout → + identical to current behavior. Zero breaking changes. + +#### 3.1.2 `UnsafeLocalCodeExecutor` — Thread + Join + Unhealthy Guard + +`exec()` cannot be interrupted from the same thread. Run it in a +daemon thread with `join(timeout)`: + +``` + ┌─ execute_code() ──────────────────────┐ + │ │ + check _healthy ───────│ if not self._healthy: raise error │ + │ │ + acquire │ with _execution_lock: │ + _execution_lock ──────│ spawn daemon thread ──► exec() │ + │ thread.join(timeout) │ + │ if thread.is_alive(): │ + │ self._healthy = False ◄── mark! │ + │ return stderr="timed out" │ + │ │ + release lock ─────────│ (lock released) │ + └────────────────────────────────────────┘ +``` + +**Critical invariant — unhealthy after timeout:** + +Simply releasing `_execution_lock` while a timed-out daemon thread is +still running would let subsequent executions proceed while the +lingering thread continues to mutate process-global `sys.stdout` and +the working directory. This causes cross-execution stdout +contamination and cwd corruption — a data-integrity bug, not just a +cosmetic issue. + +The solution is to **mark the executor unhealthy on timeout**: + +1. On timeout, set `self._healthy = False` before returning the + timeout error. The lock is released normally when the `with` block + exits. +2. Subsequent `execute_code()` calls check `self._healthy` **both + before and after** acquiring `_execution_lock` (double-check + pattern: the pre-lock check is a fast path; the post-lock check + closes the race where a caller passes the pre-lock check, waits + on the lock, and enters after another call has timed out). Both + checks **fail fast** with: `"Executor is unhealthy after a + timed-out execution. Call reinitialize() to recover."` +3. `reinitialize()` joins the lingering daemon thread with a grace + timeout (e.g., 30 s). If the thread exits, it resets + `_healthy = True` and allows execution to resume. If the thread + is **still alive** after the grace period, the executor stays + unhealthy and `reinitialize()` raises `RuntimeError` — the + caller must retry later or restart the process. + +This ensures that no new execution can run while a zombie thread is +still alive and mutating shared state. The pattern mirrors the +`ContainerCodeExecutor` unhealthy-state design (§3.1.3). + +**Trade-off:** After a timeout, the executor is unavailable until +`reinitialize()` is called. This is acceptable for a development +executor — the alternative (silent stdout/cwd corruption) is worse. +Production deployments should use `LocalSandboxCodeExecutor` (§3.2) +or `ContainerCodeExecutor`, where timeout kill is clean. + +**Why not skip thread-timeout on `UnsafeLocalCodeExecutor` entirely?** +Without any timeout, a hung `exec()` holds `_execution_lock` forever, +which is strictly worse — the executor is permanently blocked with no +error and no recovery path. The unhealthy-guard approach at least +unblocks the lock, reports the error, and offers a recovery mechanism. + +#### 3.1.3 `ContainerCodeExecutor` — Docker Exec Kill + +Run `exec_start` in a thread. On timeout, kill the process from the +host side: + +1. `exec_inspect(exec_id)` → get host-namespace PID +2. `os.kill(host_pid, SIGKILL)` +3. If `PermissionError` (common: container runs as root, ADK does not) + → `container.restart(timeout=1)` + readiness check +4. If both fail → set `self._healthy = False`, return error; caller + must call `reinitialize()` to recover + +This is the only design that guarantees the caller is never blocked +beyond `timeout` seconds, regardless of whether the kill succeeds. + +#### 3.1.4 Wire Timeout in `RunSkillScriptTool` + +Once `CodeExecutionInput.timeout_seconds` exists, the tool sets it: + +```python +CodeExecutionInput( + code=code, + input_files=input_files, + working_dir=".", + timeout_seconds=self._toolset._script_timeout, # NEW +) +``` + +This gives Python scripts the same 300-second default that shell +scripts already have, and makes it configurable via +`SkillToolset(script_timeout=N)`. The shell `subprocess.run(timeout)` +is kept as defense-in-depth. + +#### 3.1.5 Migration + +| Step | Change | Risk | +|------|--------|------| +| 1 | Add `timeout_seconds` to `CodeExecutionInput` | None | +| 2 | Add `default_timeout_seconds` to `BaseCodeExecutor` | None | +| 3 | Implement in `UnsafeLocalCodeExecutor` (thread + join) | Low | +| 4 | Implement in `ContainerCodeExecutor` (exec kill) | Low | +| 5 | Migrate `GkeCodeExecutor.timeout_seconds` to new field | None | +| 6 | Wire in `RunSkillScriptTool` | None | + +**Estimated effort:** 3-4 days (including tests). + +--- + +### 3.2 P0-B: `LocalSandboxCodeExecutor` + +**Goal:** A zero-dependency executor that provides meaningful isolation +without Docker or cloud services. + +#### 3.2.1 Why Not Just Harden `UnsafeLocalCodeExecutor`? + +We considered two alternatives before proposing a new executor: + +| Option | Approach | Why rejected | +|--------|----------|-------------| +| **Restricted builtins** | Block `open`, `__import__`, `exec`, `eval` in `exec()` globals | Trivially bypassed via `object.__subclasses__()`, `importlib` through `sys.modules`, `__builtins__.__dict__`. Not a security boundary — at best a speed bump. | +| **SecurityWarning only** | Emit `warnings.warn(SecurityWarning)` on first use | Does not reduce attack surface. Users ignore warnings. | + +Both are worth adding as **supplementary** friction (low cost, some +value), but neither solves the problem. True isolation requires a +process boundary. + +#### 3.2.2 Design: Subprocess with Resource Limits + +```python +class LocalSandboxCodeExecutor(BaseCodeExecutor): + """Executes Python in a sandboxed subprocess. + + Isolation: + - Separate process (no shared memory with host) + - Resource limits (CPU time, memory) via resource.setrlimit + - Restricted environment variables + - Temporary working directory + - Popen + communicate(timeout=N) + os.killpg for wall-clock + timeout with process-group cleanup + """ + + default_timeout_seconds: int = 30 + max_memory_mb: int = 256 + max_cpu_seconds: int = 30 + allowed_env_vars: list[str] = [] +``` + +Execution flow: + +``` + 1. Write code to a NamedTemporaryFile (.py) + 2. Write input_files to a TemporaryDirectory + 3. Build minimal env: only allowed_env_vars + PATH + 4. Popen( + ['python3', '-c', + exec(open(file).read())], + env=env, + cwd=temp_dir, + process_group=0, # Python 3.11+; preexec_fn fallback + stdout=PIPE, stderr=PIPE, + ) + 5. communicate(timeout=timeout) + 6. On TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) # kill entire group + proc.communicate(timeout=5) # reap zombies + 7. Return CodeExecutionResult(stdout, stderr) +``` + +**Why `Popen` + `os.killpg` instead of `subprocess.run(timeout)`:** + +`subprocess.run(timeout=N)` only kills the direct child process. If +the script spawns subprocesses (e.g., `os.system()`, `Popen`, +`multiprocessing`), those descendants survive the timeout and become +orphans. With `process_group=0`, the child is placed in its own +process group. On timeout, `os.killpg(proc.pid, SIGKILL)` kills the +entire group — the child and all its descendants. The follow-up +`proc.communicate(timeout=5)` reaps any zombies. + +On Python 3.10 (where `process_group` is unavailable), the fallback +uses `preexec_fn=_setup_child` where `_setup_child` calls +`os.setpgrp()` (process-group isolation) **and** sets +`resource.setrlimit` for CPU/memory. This achieves the same +kill-group semantics, with a documented caveat about fork-safety +in multi-threaded programs (see §3.2.3). + +The inline `limit_code` wrapper sets `resource.setrlimit` for CPU and +memory inside the child process (guarded with `try/except ImportError` +for platforms where `resource` is unavailable). + +**What this protects against vs. what it doesn't:** + +| Threat | Protected? | How | +|--------|-----------|-----| +| Infinite loop (direct) | Yes | Wall-clock timeout + `RLIMIT_CPU` | +| Infinite loop (child procs) | Yes | `os.killpg` kills entire process group | +| Fork bomb | **Partial** | `RLIMIT_CPU` + timeout bound total wall-clock; does not cap `RLIMIT_NPROC` (could be added) | +| Memory bomb | Yes | `RLIMIT_AS` | +| Env var / secret reading | Yes | Restricted `env` dict | +| `sys.exit()` crash | Yes | Separate process | +| Filesystem read/write | **Partial** | `cwd` is temp dir, but host fs still accessible via absolute paths | +| Network exfiltration | **No** | Requires OS-level firewall (out of scope) | + +This is strictly stronger than `UnsafeLocalCodeExecutor` across every +dimension, with zero additional dependencies. The remaining gaps +(full filesystem isolation, network restriction, `RLIMIT_NPROC`) +require containers or OS-level policy. + +#### 3.2.3 Platform Considerations + +- **Python 3.11+:** Use `process_group=0` (fork-safe, replaces + `preexec_fn`). Enables clean `os.killpg()` on timeout. +- **Python 3.10:** Fall back to `preexec_fn=_setup_child` where + `_setup_child` calls `os.setpgrp()` (new process group, required + for `os.killpg` on timeout) **and** sets `resource.setrlimit` for + CPU/memory. Documented caveat: `preexec_fn` is not fork-safe in + multi-threaded programs. ADK minimum is `>=3.10` per + `pyproject.toml`. +- **Windows:** Not supported. Raise `NotImplementedError` directing + users to `ContainerCodeExecutor`. (`resource.setrlimit` and + `process_group` are Unix-only.) + +#### 3.2.4 Migration + +| Step | Change | Risk | +|------|--------|------| +| 1 | Implement `LocalSandboxCodeExecutor` | Low | +| 2 | Add `SecurityWarning` to `UnsafeLocalCodeExecutor` | None | +| 3 | Add `restrict_builtins` option (opt-in, supplementary) | Low | +| 4 | Update samples and `adk web` defaults to recommend sandbox | Low | +| 5 | Update documentation | None | + +**Estimated effort:** 5-7 days (including tests and docs). + +--- + +## 4. Alternatives Considered + +### 4.1 "Do Nothing — Document the Risks" + +Add warnings to docs and let users choose their executor. + +**Rejected.** Samples, tutorials, and common development workflows +use `UnsafeLocalCodeExecutor` for local code execution. New users +follow sample code without reading security docs. The executor most +commonly reached by new developers must be safe enough for its +intended use (local development with untrusted LLM-generated code). + +### 4.2 "Require Docker for All Local Execution" + +Make `ContainerCodeExecutor` the default. Remove +`UnsafeLocalCodeExecutor`. + +**Rejected.** Docker is a significant dependency. Many developers +(especially on macOS) don't have it installed. CI environments +may not have Docker available. The zero-dependency story is a key +ADK differentiator for onboarding. We need a middle ground. + +### 4.3 "Timeout Only, No New Executor" + +Ship P0-A (timeout) without P0-B (sandbox). Defer security to a +later phase. + +**Viable but insufficient.** Timeout prevents DoS but does not +prevent data exfiltration, secret reading, or filesystem manipulation. +These are the higher-impact threats for skill scripts, which may come +from third-party authors. We recommend shipping both P0-A and P0-B, +but they are independently valuable and can be phased if needed. + +--- + +## 5. Rollout Plan + +### 5.1 Phase 1: Timeout Foundation (Week 1) + +| Day | Deliverable | +|-----|-------------| +| 1 | Add `timeout_seconds` to `CodeExecutionInput` and `default_timeout_seconds` to `BaseCodeExecutor`. Unit tests for field defaults and resolution logic. | +| 2 | Implement thread-based timeout in `UnsafeLocalCodeExecutor`. Tests with `time.sleep()` scripts. | +| 3 | Implement Docker exec kill in `ContainerCodeExecutor` with `_healthy` guard and `reinitialize()`. Mock-based tests for kill path, permission error path, and total failure path. | +| 4 | Migrate `GkeCodeExecutor`, wire `RunSkillScriptTool`, end-to-end integration tests. | + +**Exit criteria:** `RunSkillScriptTool` Python scripts respect +`script_timeout`. Existing tests pass. No behavioral change for +callers that don't set timeout. + +### 5.2 Phase 2: Security Hardening (Week 2) + +| Day | Deliverable | +|-----|-------------| +| 1-2 | Implement `LocalSandboxCodeExecutor` with resource limits. | +| 3 | Add `SecurityWarning` to `UnsafeLocalCodeExecutor`. Add `restrict_builtins` opt-in. | +| 4 | Tests: resource limit enforcement, env var isolation, timeout kill via `os.killpg`, platform fallback for 3.10. | +| 5 | Update samples, docs, and recommendation matrix. | + +**Exit criteria:** `LocalSandboxCodeExecutor()` works as a drop-in +replacement for `UnsafeLocalCodeExecutor()` for the supported script +profile: scripts that use stdout/stderr for output, do not depend on +host environment variables beyond an explicit allowlist, and access +files only within the sandbox working directory. Scripts that rely on +broad host-filesystem access or specific env vars will need to +configure `allowed_env_vars` or use `UnsafeLocalCodeExecutor`. +Documentation recommends `LocalSandboxCodeExecutor` for all new local +development and clearly states the compatibility envelope. + +### 5.3 Recommendation Matrix (Post-Rollout) + +| Use Case | Executor | Why | +|----------|----------|-----| +| Local development | `LocalSandboxCodeExecutor` | Zero deps, subprocess isolation | +| Quick prototyping (trusted code) | `UnsafeLocalCodeExecutor` | Fastest, no isolation | +| CI/CD | `ContainerCodeExecutor` | Docker available in CI | +| Production (single tenant) | `ContainerCodeExecutor` | Full container isolation | +| Production (multi-tenant) | `GkeCodeExecutor` | gVisor, per-execution isolation | +| Google Cloud | `AgentEngineSandboxCodeExecutor` | Managed, scalable | + +### 5.4 Success Metrics + +- **Timeout coverage:** 100% of executors support `timeout_seconds` + (currently 1 of 5). +- **Default safety:** `LocalSandboxCodeExecutor` passes all existing + `RunSkillScriptTool` integration tests that fit the supported script + profile (stdout/stderr output, sandbox-local file access, no + dependency on host env vars beyond allowlist). +- **No regressions:** All existing unit and integration tests pass + with zero behavioral changes for callers that don't opt in. +- **Adoption signal:** Samples and `adk web` default documentation + reference `LocalSandboxCodeExecutor`. + +--- + +## Appendix A: Current RunSkillScriptTool Execution Flow + +``` +LLM calls run_skill_script(skill_name, script_path, args) + │ + ▼ +RunSkillScriptTool.run_async() + │ + ├─ Validate params (skill_name, script_path, args type) + ├─ Resolve skill → resolve script from resources + ├─ Resolve executor: toolset._code_executor → agent.code_executor + ├─ Package ALL skill files as input_files (refs, assets, scripts) + ├─ _prepare_code(): + │ .py → runpy.run_path() wrapper (NO timeout) + │ .sh → subprocess.run(timeout=N) wrapper with JSON envelope + │ + ├─ await asyncio.to_thread(executor.execute_code, ...) + │ CodeExecutionInput(code=..., input_files=..., working_dir=".") + │ *** timeout_seconds NOT SET — this is the gap *** + │ + ├─ Parse result: + │ Shell: unpack JSON envelope {stdout, stderr, returncode} + │ Python: use stdout/stderr directly + │ + └─ Return {skill_name, script_path, stdout, stderr, status} +``` + +## Appendix B: Key Source Files + +| File | Role | +|------|------| +| `src/google/adk/tools/skill_toolset.py` | `RunSkillScriptTool`, `SkillToolset` | +| `src/google/adk/code_executors/base_code_executor.py` | `BaseCodeExecutor` abstract class | +| `src/google/adk/code_executors/code_execution_utils.py` | `CodeExecutionInput`, `CodeExecutionResult`, `File` | +| `src/google/adk/code_executors/unsafe_local_code_executor.py` | Current local executor | +| `src/google/adk/code_executors/container_code_executor.py` | Docker-based executor | +| `src/google/adk/code_executors/gke_code_executor.py` | GKE-based executor (has timeout) | +| `tests/unittests/tools/test_skill_toolset.py` | ~1170-line test suite for skill tools | +| `docs/design/code_executor_enhancements.md` | Detailed design doc (companion to this RFC) | diff --git a/docs/design/skill_execution_script.md b/docs/design/skill_execution_script.md new file mode 100644 index 0000000000..ae269b0f0b --- /dev/null +++ b/docs/design/skill_execution_script.md @@ -0,0 +1,370 @@ + + +# Summary + +This outlines the design for adding pre-registered function execution within ADK’s non-bash based skills toolset. + +# Motivation + +ADK Skills provide a way to package instructions, resources, and scripts to extend agent capabilities. While skills can guide an agent's reasoning, the ability to execute code within the skill's context unlocks more powerful actions. This requires a secure and well-defined execution environment. + +We also want to support adapting existing `BaseTool` or `FunctionTool` instances, making them available as part of the Skill interface. + +# Proposal + +There are two parts to the proposal for pre-registered function execution: + +1. Allow SkillToolset to include **additional ADK tools/functions** that are specified by the skill: adapting existing BaseTool and FunctionTool interfaces so that users can feed in existing functions +2. Enable **script execution** (i.e. files in skill/scripts) with RunSkillScriptTool + +## Enabling usage of ADK tools + +Users should be able to pass in existing ADK tools (both built-in and custom) as BaseTool objects and have them be used within a skill. To do this, we can use the [allowed\_tools]field of a skill’s frontmatter to determine which tools should be instantiated. + +Within SkillToolset, we can modify the signature to accept an optional `additional_tools` argument that allows users to pass in pre-instantiated tools, toolsets, or callables. Then we can update `SkillToolset.get_tools()` to dynamically resolve the tools in allowed\_tools for all skills in the toolset. We will iterate through the skill’s allowed tools and check if any of the `additional_tools` match, and add them to the toolset if so. As a fallback, we will also check if the tools exist as built-in tools in the google.adk.tools directory. + +Since get\_tools() is called every invocation, we will also cache the tools so we don’t have to resolve them every time. + +```py +class SkillToolset(BaseToolset): + def __init__( + self, + skills: list[models.Skill], + additional_tools: list[ToolUnion] = None, + ): + ... + + def get_tools(self, readonly_context) -> list[BaseTool]: + # Collect allowed tools from skills + allowed_tool_names = set() + for skill in self.skills: + if skill.frontmatter.allowed_tools: + allowed_tool_names.update([name for name in skill.frontmatter.allowed_tools]) + + # Resolve tools passed in with `additional_tools` + tools_by_name = {} + for tool_union in self._additional_tools: + if isinstance(tool_union, BaseTool): + tools_by_name[tool_union.name] = tool_union + if isinstance(tool_union, BaseToolset): + ts_tools = await tool_union.get_tools(readonly_context) + for t in ts_tools: + tools_by_name[t.name] = t + elif callable(tool_union): + tools_by_name[tool_union.name] = FunctionTool(tool_union) + + for allowed_tool in allowed_tool_names: + # add tools from tools_by_name or if they don't exist, + # try to resolve using built-in tools in the google.adk.tools directory + ... +``` + +## Enabling Script Execution + +We will integrate script execution into `SkillToolset` by using the existing [BaseCodeExecutor] interface. +We can modify `SkillToolset` to accept an optional code\_executor argument and create a new tool, `RunSkillScriptTool`, that will be used for script execution: + +```py +class SkillToolset(BaseToolset): + def __init__( + self, + skills: list[models.Skill], + code_executor: Optional[base_code_executor.BaseCodeExecutor] = None, + ): + super().__init__() + self._skills = {skill.name: skill for skill in skills} + self._code_executor = code_executor + + self._tools = [LoadSkillTool(self), LoadSkillResourceTool(self)] + # Add RunSkillScriptTool for function execution + if self._code_executor: + self._tools.append(RunSkillScriptTool(self)) +``` + +`RunSkillScriptTool` will be used for script execution. It will take a toolset and script\_metadata as input. + +```py +class RunSkillScriptTool(BaseTool): + def __init__(self, toolset: "SkillToolset", script_metadata: Dict[str, Any] = None): + # Initialize the tool + pass + + def _get_declaration(self) -> types.FunctionDeclaration | None: + params_schema = { + "type": "object", + "properties": { + "skill_name": { + "type": "string", + "description": "The name of the skill." + }, + "script_path": { + "type": "string", + "description": "The relative path to the script (e.g., 'scripts/my_script.py' or 'scripts/setup.sh')." + }, + "args": { + "type": "object", + "description": "Optional arguments to pass to the script as key-value pairs." + }, + }, + "required": ["skill_name", "script_path"], + } + return types.FunctionDeclaration( + name=self.name, + description=self.description, + parameters_json_schema=params_schema + ) + + async def run_async(self, *, args: dict[str, Any], tool_context: ToolContext) -> Any: + # 1. Validate inputs (skill_name, script_path) + # 2. Extract script and arguments Map + # 3. Mount all skill files (assets, references, scripts) as input_files + # 4. Set sandbox_working_dir to the sandbox root '.' + # 5. Generate safe subprocess wrappers or sys.argv injections + # 6. Execute via BaseCodeExecutor matching toolset configuration + ... +``` + +**Script Invocation:** Arguments are passed to the script similar to command-line arguments, by mocking `sys.argv`. The script's standard output, standard error, and any resulting files will be captured by the executor. + +**Executor Choices:** The `SkillToolset` can be configured with any ADK `BaseCodeExecutor` instance. Recommended executors include VertexAiCodeExecutor (executes code in a secure Vertex AI sandbox) and GkeCodeExecutor (executes code in a gVisor sandbox on GKE). + +### Adapting BaseCodeExecutor + +The current `BaseCodeExecutor` interface is designed for executing LLM-generated code snippets. To effectively support `RunSkillScriptTool`, we should consider file system context and path resolution: + +`BaseCodeExecutor`'s `execute_code` method doesn't have a way to inform the execution environment about the skill's file structure. Scripts within a skill will likely need to read from `../references/` or `../assets/` using relative paths. The sandbox needs to honor these paths relative to the skill's root or the `scripts/` directory. + +We can extend the `File` Dataclass in `code_execution_utils.py` to include a `path`: + +```py +@dataclasses.dataclass(frozen=True) +class File: + """A structure that contains a file name and its content.""" + name: str # Base name of the file + content: str | bytes + mime_type: str = 'text/plain' + path: Optional[str] = None # Native relative path (e.g. 'references/guidelines.md') +``` + +We will also extend `CodeExecutionInput` to add a `working_dir`: + +```py +@dataclasses.dataclass +class CodeExecutionInput: + code: str + input_files: list[File] = dataclasses.field(default_factory=list) + execution_id: Optional[str] = None + working_dir: Optional[str] = None # e.g., '/skill/scripts' +``` + +`RunSkillScriptTool` will package the Skill’s resources into input\_files to add to the CodeExecutionInput. Within the BaseCodeExecutor implementations (VertexAI, GKE, etc), we will then: + +* Read input\_files. For each `File` with sandbox\_path, create the file and any necessary parent directories at the exact path in the sandbox +* Set the sandbox working directory to sandbox\_working\_dir + +#### File Permissions + +Files/directories created within the sandbox from the skill’s `references/` and `assets/` should be read-only for the executed script. The script should have write-access to a dedicated temp directory in the sandbox and potentially a designated output directory. + +#### Other Considerations + +The CodeExecutor and sandbox environment will address most script execution issues: + +* Resource limits are enforced by sandbox env +* Network access disabled by default +* **Output files:** Files will be created in output directory and returned in `CodeExecutionResult.output_files` +* **Error handling:** Report script exceptions, exit codes, executor errors through `CodeExecutionResult.stderr` + * Add error post-processing: we will implement an ‘LLM-friendly’ error formatter. Instead of returning the full traceback, the tool will extract the specific Exception type and the offending line of code to help the agent self-correct its script invocation. + +## RunSkillScriptTool — Design Details & Considerations + +### Overview + +`RunSkillScriptTool` enables ADK agents to execute scripts bundled inside a +skill's `scripts/` directory via ADK's `BaseCodeExecutor` infrastructure. This +closes the gap between the +[Agent Skills spec](https://agentskills.io/specification) (which defines +`scripts/` as an optional skill resource) and ADK's runtime capabilities. By +mounting skill dependencies including `references/` and `assets/`, +`RunSkillScriptTool` executes skills in sandboxed environments with full access +to their context. + +### Architecture + +``` +LLM calls run_skill_script(skill_name, script_path, args) + │ + ▼ +┌─ RunSkillScriptTool.run_async() ─────────────────────┐ +│ 1. Validate params & resolve skill/script │ +│ 2. Resolve code executor (toolset → agent fallback) │ +│ 3. Validate args (handled natively by JSON schema) │ +│ 4. Mount dependencies (assets, references, scripts) │ +│ 5. _prepare_code() → generate Python wrapper code │ +│ 6. code_executor.execute_code(..., input_files=...) │ +│ 7. Parse result (JSON envelope for shell scripts) │ +│ 8. Return {stdout, stderr, status} to LLM │ +└───────────────────────────────────────────────────────────┘ +``` + +### Parameter Schema Design + +The tool employs specific parameter designs to ensure safe sandboxed execution +and high LLM reliability: + +1. **`script_path` vs `script_name`:** \ + Instead of a flat `script_name` (e.g. `setup.sh`), the tool requires the + full relative `script_path` (e.g. `scripts/setup.sh` or + `scripts/utils/helper.py`). This is required because the tool mounts the + entire skill directory into the execution sandbox, meaning the script must + be invoked from the true sandbox root path so it can reliably access its + `assets/` and `references/` via relative paths. + +2. **`args` Dictionary:** \ + Instead of taking a raw array of string arguments (`["--verbose", + "--force"]`), the tool takes a structured key-value `args` object + (`{"verbose": true, "force": true}`). LLMs are significantly more reliable + at generating structured JSON objects than raw command-line flag arrays. + Furthermore, accepting an object moves the burden of secure structural + flattening (e.g. constructing the `['--verbose', 'True']` array) to the + Python code, completely eliminating a class of shell-injection + vulnerabilities. + +### Script Type Handling + +Type | Extension | Execution Method | Timeout | Args Injection +:----- | :------------- | :---------------------------------------------------- | :--------------------- | :------------- +Python | `.py` | Direct `exec()` via code executor | No (executor-level) | `sys.argv = [script_path] + mapped_args` +Shell | `.sh`, `.bash` | `subprocess.run(['bash', script_path] + mapped_args)` | Yes (`script_timeout`) | `args` parsed as sequence of flattened pairs +Other | any | Rejected | N/A | N/A + +**Extensionless files are rejected** (not silently treated as Python) to avoid +unexpected behavior. + +### Code Executor Resolution Chain + +``` +1. SkillToolset(code_executor=...) ← explicit, highest priority +2. agent.code_executor ← fallback to agent's executor +3. None → return NO_CODE_EXECUTOR ← actionable error +``` + +This design allows a single toolset-level executor to be shared across all +skills, or per-agent executors for different isolation levels. + +### Shell Script JSON Envelope + +Shell scripts face a unique challenge: `UnsafeLocalCodeExecutor` captures stdout +via `redirect_stdout(StringIO)`, but if the generated code raises an exception, +`stdout.getvalue()` is never called and stdout is lost. This means a naive +`raise RuntimeError(stderr)` approach discards any stdout the script produced. + +Crucially, **even when running inside a secure sandbox** (like Vertex AI Code +Interpreter), sandboxes often struggle to cleanly report *why* an arbitrary +script failed if the script loops infinitely or crashes aggressively. An abrupt +exit often yields a generic "sandbox failed" error, denying the LLM the context +it needs to self-correct. + +**Solution**: The Python subprocess wrapper we inject *around* the script +executes the shell command safely and serializes both stdout and stderr as a +JSON envelope through the single stdout channel. + +Even inside a sandbox environment, our wrapper catches the shell script's output +in real-time. If the shell script times out inside the sandbox, our wrapper +catches the `TimeoutExpired` exception, scoops up whatever output the shell +script produced *before* it hung, packages it into JSON, and returns that +perfectly structured payload to the Executor. This guarantees the LLM always +receives perfectly exact `stdout` and `stderr` logs regardless of script +crashes. + +```py +# Generated code for shell scripts: +import subprocess, shlex, json as _json +try: + _r = subprocess.run( + ['bash', SCRIPT_PATH] + MAPPED_ARGS, + capture_output=True, text=True, + timeout=SCRIPT_TIMEOUT, + ) + print(_json.dumps({ + '__shell_result__': True, + 'stdout': _r.stdout, + 'stderr': _r.stderr, + 'returncode': _r.returncode, + })) +except subprocess.TimeoutExpired as _e: + print(_json.dumps({ + '__shell_result__': True, + 'stdout': _e.stdout or '', + 'stderr': 'Timed out after Ns', + 'returncode': -1, + })) +``` + +`run_async()` then parses this JSON envelope (only for shell scripts, keyed on +`__shell_result__`) to extract both streams and the return code. This works +reliably with both `UnsafeLocalCodeExecutor` and container-based executors. + +### Three-State Status Model + +Status | Condition +:-------- | :------------------------------------------------------------- +`success` | No stderr +`warning` | Both stdout and stderr present (e.g., deprecation warnings) +`error` | Stderr only (no stdout), or non-zero returncode with no stdout + +### Security Considerations + +**Shell injection prevention:** + +- **Structured Argument Arrays:** `args` is passed as a structured dictionary + by the LLM natively. The tool converts these into strict, flattened string + arrays `['--key', 'value']` and passes them securely to `subprocess.run` + with `shell=False`. Because the elements are passed as a strict array, the + underlying OS treats flags and values as literal parameters passed *into* + the script, meaning any malicious shell operators (e.g. `&&`, `|`) are + treated as literal strings and ignored. +- The script source is executed as an isolated file path inside the sandboxed + `$working_dir`. + +**`SystemExit` handling:** + +- `sys.exit()` raises `SystemExit(BaseException)`, which is NOT caught by + `except Exception` in executors +- `run_async()` explicitly catches `SystemExit` to prevent skill scripts from + terminating the host process +- `sys.exit(0)` and `sys.exit(None)` are treated as successful termination +- Non-zero exit codes return `EXECUTION_ERROR` + +**Executor security:** + +- `UnsafeLocalCodeExecutor` runs code in the host process via `exec()` — + suitable only for trusted, first-party skills +- For third-party or untrusted skills, a sandboxed executor (e.g., + `ContainerCodeExecutor`) should be used +- The sample agent includes explicit warnings about this + +### Known Limitations & Future Work + +1. **No timeout for Python scripts**: `exec()` provides no built-in timeout + mechanism. A malicious/buggy Python script can hang indefinitely. This is an + executor-level concern — solving it properly requires running Python scripts + in a subprocess or implementing executor-level cancellation. + +2. **Python script stdout lost on exception**: When a Python script writes to + stdout and then raises, `UnsafeLocalCodeExecutor` loses the stdout (same + root cause as the shell fix). This is less critical for Python since + exceptions are the natural error mechanism, but could be improved at the + executor level. + +### Error Codes Reference + +Error Code | Meaning +:------------------------ | :--------------------------------------------- +`MISSING_SKILL_NAME` | `skill_name` parameter not provided +`MISSING_SCRIPT_PATH` | `script_path` parameter not provided +`SKILL_NOT_FOUND` | No skill with that name registered +`SCRIPT_NOT_FOUND` | No script with that name in the skill +`NO_CODE_EXECUTOR` | No code executor configured (toolset or agent) +`UNSUPPORTED_SCRIPT_TYPE` | File extension not `.py`, `.sh`, or `.bash` +`EXECUTION_ERROR` | Runtime error, non-zero exit, or `sys.exit(N)` diff --git a/src/google/adk/code_executors/vertex_ai_code_executor.py b/src/google/adk/code_executors/vertex_ai_code_executor.py index 67c42ed8f2..a6a0ec8eb5 100644 --- a/src/google/adk/code_executors/vertex_ai_code_executor.py +++ b/src/google/adk/code_executors/vertex_ai_code_executor.py @@ -1,4 +1,4 @@ -# Copyright 2026 Google LLC +# Copyright 2025 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/src/google/adk/tools/skill_toolset.py b/src/google/adk/tools/skill_toolset.py index f90dfdb2b1..d13481eba3 100644 --- a/src/google/adk/tools/skill_toolset.py +++ b/src/google/adk/tools/skill_toolset.py @@ -12,16 +12,24 @@ # See the License for the specific language governing permissions and # limitations under the License. +# pylint: disable=g-import-not-at-top,protected-access + """Toolset for discovering, viewing, and executing agent skills.""" from __future__ import annotations +import asyncio +import json +import logging from typing import Any +from typing import Optional from typing import TYPE_CHECKING from google.genai import types from ..agents.readonly_context import ReadonlyContext +from ..code_executors.base_code_executor import BaseCodeExecutor +from ..code_executors.code_execution_utils import CodeExecutionInput from ..features import experimental from ..features import FeatureName from ..skills import models @@ -33,6 +41,11 @@ if TYPE_CHECKING: from ..models.llm_request import LlmRequest +logger = logging.getLogger("google_adk." + __name__) + +_DEFAULT_SCRIPT_TIMEOUT = 300 +_MAX_SKILL_PAYLOAD_BYTES = 16 * 1024 * 1024 # 16 MB + DEFAULT_SKILL_SYSTEM_INSTRUCTION = """You can use specialized 'skills' to help you with complex tasks. You MUST use the skill tools to interact with these skills. Skills are folders of instructions and resources that extend your capabilities for specialized tasks. Each skill folder contains: @@ -46,6 +59,7 @@ 1. If a skill seems relevant to the current user query, you MUST use the `load_skill` tool with `name=""` to read its full instructions before proceeding. 2. Once you have read the instructions, follow them exactly as documented before replying to the user. For example, If the instruction lists multiple steps, please make sure you complete all of them in order. 3. The `load_skill_resource` tool is for viewing files within a skill's directory (e.g., `references/*`, `assets/*`, `scripts/*`). Do NOT use other tools to access these files. +4. Use `run_skill_script` to run scripts from a skill's `scripts/` directory. Use `load_skill_resource` to view script content first if needed. """ @@ -227,6 +241,340 @@ async def run_async( } +class _SkillScriptCodeExecutor: + """A helper that materializes skill files and executes scripts.""" + + _base_executor: BaseCodeExecutor + _script_timeout: int + + def __init__(self, base_executor: BaseCodeExecutor, script_timeout: int): + self._base_executor = base_executor + self._script_timeout = script_timeout + + async def execute_script_async( + self, + invocation_context: Any, + skill: models.Skill, + script_path: str, + script_args: dict[str, Any], + ) -> dict[str, Any]: + """Prepares and executes the script using the base executor.""" + code = self._build_wrapper_code(skill, script_path, script_args) + if code is None: + if "." in script_path: + ext_msg = f"'.{script_path.rsplit('.', 1)[-1]}'" + else: + ext_msg = "(no extension)" + return { + "error": ( + f"Unsupported script type {ext_msg}." + " Supported types: .py, .sh, .bash" + ), + "error_code": "UNSUPPORTED_SCRIPT_TYPE", + } + + try: + # Execute the self-contained script using the underlying executor + result = await asyncio.to_thread( + self._base_executor.execute_code, + invocation_context, + CodeExecutionInput(code=code), + ) + + stdout = result.stdout + stderr = result.stderr + + # Shell scripts serialize both streams as JSON + # through stdout; parse the envelope if present. + rc = 0 + is_shell = "." in script_path and script_path.rsplit(".", 1)[ + -1 + ].lower() in ("sh", "bash") + if is_shell and stdout: + try: + parsed = json.loads(stdout) + if isinstance(parsed, dict) and parsed.get("__shell_result__"): + stdout = parsed.get("stdout", "") + stderr = parsed.get("stderr", "") + rc = parsed.get("returncode", 0) + if rc != 0 and not stderr: + stderr = f"Exit code {rc}" + except (json.JSONDecodeError, ValueError): + pass + + status = "success" + if rc != 0: + status = "error" + elif stderr and not stdout: + status = "error" + elif stderr: + status = "warning" + + return { + "skill_name": skill.name, + "script_path": script_path, + "stdout": stdout, + "stderr": stderr, + "status": status, + } + except SystemExit as e: + if e.code in (None, 0): + return { + "skill_name": skill.name, + "script_path": script_path, + "stdout": "", + "stderr": "", + "status": "success", + } + return { + "error": ( + f"Failed to execute script '{script_path}':" + f" exited with code {e.code}" + ), + "error_code": "EXECUTION_ERROR", + } + except Exception as e: # pylint: disable=broad-exception-caught + logger.exception( + "Error executing script '%s' from skill '%s'", + script_path, + skill.name, + ) + short_msg = str(e) + if len(short_msg) > 200: + short_msg = short_msg[:200] + "..." + return { + "error": ( + "Failed to execute script" + f" '{script_path}':\n{type(e).__name__}:" + f" {short_msg}" + ), + "error_code": "EXECUTION_ERROR", + } + + def _build_wrapper_code( + self, + skill: models.Skill, + script_path: str, + script_args: dict[str, Any], + ) -> str | None: + """Builds a self-extracting Python script.""" + ext = "" + if "." in script_path: + ext = script_path.rsplit(".", 1)[-1].lower() + + if not script_path.startswith("scripts/"): + script_path = f"scripts/{script_path}" + + files_dict = {} + for ref_name in skill.resources.list_references(): + content = skill.resources.get_reference(ref_name) + if content is not None: + files_dict[f"references/{ref_name}"] = content + + for asset_name in skill.resources.list_assets(): + content = skill.resources.get_asset(asset_name) + if content is not None: + files_dict[f"assets/{asset_name}"] = content + + for scr_name in skill.resources.list_scripts(): + scr = skill.resources.get_script(scr_name) + if scr is not None and scr.src is not None: + files_dict[f"scripts/{scr_name}"] = scr.src + + total_size = sum( + len(v) if isinstance(v, (str, bytes)) else 0 + for v in files_dict.values() + ) + if total_size > _MAX_SKILL_PAYLOAD_BYTES: + logger.warning( + "Skill '%s' resources total %d bytes, exceeding" + " the recommended limit of %d bytes.", + skill.name, + total_size, + _MAX_SKILL_PAYLOAD_BYTES, + ) + + # Build the boilerplate extract string + code_lines = [ + "import os", + "import tempfile", + "import sys", + "import json as _json", + "import subprocess", + "import runpy", + f"_files = {files_dict!r}", + "def _materialize_and_run():", + " _orig_cwd = os.getcwd()", + " with tempfile.TemporaryDirectory() as td:", + " for rel_path, content in _files.items():", + " full_path = os.path.join(td, rel_path)", + " os.makedirs(os.path.dirname(full_path), exist_ok=True)", + " mode = 'wb' if isinstance(content, bytes) else 'w'", + " with open(full_path, mode) as f:", + " f.write(content)", + " os.chdir(td)", + " try:", + ] + + if ext == "py": + argv_list = [script_path] + for k, v in script_args.items(): + argv_list.extend([f"--{k}", str(v)]) + code_lines.extend([ + f" sys.argv = {argv_list!r}", + " try:", + f" runpy.run_path({script_path!r}, run_name='__main__')", + " except SystemExit as e:", + " if e.code is not None and e.code != 0:", + " raise e", + ]) + elif ext in ("sh", "bash"): + arr = ["bash", script_path] + for k, v in script_args.items(): + arr.extend([f"--{k}", str(v)]) + timeout = self._script_timeout + code_lines.extend([ + " try:", + " _r = subprocess.run(", + f" {arr!r},", + " capture_output=True, text=True,", + f" timeout={timeout!r}, cwd=td,", + " )", + " print(_json.dumps({", + " '__shell_result__': True,", + " 'stdout': _r.stdout,", + " 'stderr': _r.stderr,", + " 'returncode': _r.returncode,", + " }))", + " except subprocess.TimeoutExpired as _e:", + " print(_json.dumps({", + " '__shell_result__': True,", + " 'stdout': _e.stdout or '',", + f" 'stderr': 'Timed out after {timeout}s',", + " 'returncode': -1,", + " }))", + ]) + else: + return None + + code_lines.extend([ + " finally:", + " os.chdir(_orig_cwd)", + ]) + + code_lines.append("_materialize_and_run()") + return "\n".join(code_lines) + + +@experimental(FeatureName.SKILL_TOOLSET) +class RunSkillScriptTool(BaseTool): + """Tool to execute scripts from a skill's scripts/ directory.""" + + def __init__(self, toolset: "SkillToolset"): + super().__init__( + name="run_skill_script", + description="Executes a script from a skill's scripts/ directory.", + ) + self._toolset = toolset + + def _get_declaration(self) -> types.FunctionDeclaration | None: + return types.FunctionDeclaration( + name=self.name, + description=self.description, + parameters_json_schema={ + "type": "object", + "properties": { + "skill_name": { + "type": "string", + "description": "The name of the skill.", + }, + "script_path": { + "type": "string", + "description": ( + "The relative path to the script (e.g.," + " 'scripts/setup.py')." + ), + }, + "args": { + "type": "object", + "description": ( + "Optional arguments to pass to the script as key-value" + " pairs." + ), + }, + }, + "required": ["skill_name", "script_path"], + }, + ) + + async def run_async( + self, *, args: dict[str, Any], tool_context: ToolContext + ) -> Any: + skill_name = args.get("skill_name") + script_path = args.get("script_path") + script_args = args.get("args", {}) + if not isinstance(script_args, dict): + return { + "error": ( + "'args' must be a JSON object (key-value pairs)," + f" got {type(script_args).__name__}." + ), + "error_code": "INVALID_ARGS_TYPE", + } + + if not skill_name: + return { + "error": "Skill name is required.", + "error_code": "MISSING_SKILL_NAME", + } + if not script_path: + return { + "error": "Script path is required.", + "error_code": "MISSING_SCRIPT_PATH", + } + + skill = self._toolset._get_skill(skill_name) + if not skill: + return { + "error": f"Skill '{skill_name}' not found.", + "error_code": "SKILL_NOT_FOUND", + } + + script = None + if script_path.startswith("scripts/"): + script = skill.resources.get_script(script_path[len("scripts/") :]) + else: + script = skill.resources.get_script(script_path) + + if script is None: + return { + "error": f"Script '{script_path}' not found in skill '{skill_name}'.", + "error_code": "SCRIPT_NOT_FOUND", + } + + # Resolve code executor: toolset-level first, then agent fallback + code_executor = self._toolset._code_executor + if code_executor is None: + agent = tool_context._invocation_context.agent + if hasattr(agent, "code_executor"): + code_executor = agent.code_executor + if code_executor is None: + return { + "error": ( + "No code executor configured. A code executor is" + " required to run scripts." + ), + "error_code": "NO_CODE_EXECUTOR", + } + + script_executor = _SkillScriptCodeExecutor( + code_executor, self._toolset._script_timeout # pylint: disable=protected-access + ) + return await script_executor.execute_script_async( + tool_context._invocation_context, skill, script_path, script_args # pylint: disable=protected-access + ) + + @experimental(FeatureName.SKILL_TOOLSET) class SkillToolset(BaseToolset): """A toolset for managing and interacting with agent skills.""" @@ -234,7 +582,19 @@ class SkillToolset(BaseToolset): def __init__( self, skills: list[models.Skill], + *, + code_executor: Optional[BaseCodeExecutor] = None, + script_timeout: int = _DEFAULT_SCRIPT_TIMEOUT, ): + """Initializes the SkillToolset. + + Args: + skills: List of skills to register. + code_executor: Optional code executor for script execution. + script_timeout: Timeout in seconds for shell script execution via + subprocess.run. Defaults to 300 seconds. Does not apply to Python + scripts executed via exec(). + """ super().__init__() # Check for duplicate skill names @@ -245,11 +605,17 @@ def __init__( seen.add(skill.name) self._skills = {skill.name: skill for skill in skills} + self._code_executor = code_executor + self._script_timeout = script_timeout + + # Initialize core skill tools self._tools = [ ListSkillsTool(self), LoadSkillTool(self), LoadSkillResourceTool(self), ] + # Always add RunSkillScriptTool, relies on invocation_context fallback if _code_executor is None + self._tools.append(RunSkillScriptTool(self)) async def get_tools( self, readonly_context: ReadonlyContext | None = None diff --git a/tests/unittests/benchmarks/__init__.py b/tests/unittests/benchmarks/__init__.py new file mode 100644 index 0000000000..58d482ea38 --- /dev/null +++ b/tests/unittests/benchmarks/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/unittests/benchmarks/bigquerybench/__init__.py b/tests/unittests/benchmarks/bigquerybench/__init__.py new file mode 100644 index 0000000000..58d482ea38 --- /dev/null +++ b/tests/unittests/benchmarks/bigquerybench/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/tests/unittests/benchmarks/bigquerybench/test_metrics.py b/tests/unittests/benchmarks/bigquerybench/test_metrics.py new file mode 100644 index 0000000000..1f444b85f0 --- /dev/null +++ b/tests/unittests/benchmarks/bigquerybench/test_metrics.py @@ -0,0 +1,348 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for BigQueryBench metrics including LLM-as-judge adherence.""" + +import json +from unittest import mock + +from google.adk.evaluation.eval_case import IntermediateData +from google.adk.evaluation.eval_case import Invocation +from google.adk.evaluation.eval_metrics import EvalMetric +from google.adk.evaluation.eval_metrics import EvalStatus +from google.adk.evaluation.eval_rubrics import Rubric +from google.adk.evaluation.eval_rubrics import RubricContent +from google.adk.evaluation.eval_set import EvalSet +from google.genai import types as genai_types +import pytest + +from benchmarks.bigquerybench.metrics import instruction_adherence_score +from benchmarks.bigquerybench.metrics import tool_args_score +from benchmarks.bigquerybench.metrics import tool_invocation_score + + +def _make_content(text: str) -> genai_types.Content: + return genai_types.Content(parts=[genai_types.Part(text=text)], role="user") + + +def _make_invocation( + tool_calls: list[dict], + user_text: str = "test", + final_text: str = "", +) -> Invocation: + tool_uses = [] + for tc in tool_calls: + tool_uses.append( + genai_types.FunctionCall(name=tc["name"], args=tc.get("args", {})) + ) + inv = Invocation( + invocation_id="inv-test", + user_content=_make_content(user_text), + intermediate_data=IntermediateData(tool_uses=tool_uses), + ) + if final_text: + inv.final_response = genai_types.Content( + parts=[genai_types.Part(text=final_text)], role="model" + ) + return inv + + +# ── tool_invocation_score tests ──────────────────────────────────── + + +class TestToolInvocationScore: + + def test_all_expected_tools_present(self): + metric = EvalMetric(metric_name="test") + actual = [ + _make_invocation([ + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}}, + {"name": "load_skill_resource", "args": {"skill_name": "x"}}, + ]) + ] + expected = [ + _make_invocation([ + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}}, + {"name": "load_skill_resource", "args": {"skill_name": "x"}}, + ]) + ] + result = tool_invocation_score(metric, actual, expected) + assert result.overall_score == 1.0 + assert result.overall_eval_status == EvalStatus.PASSED + + def test_missing_expected_tool(self): + metric = EvalMetric(metric_name="test") + actual = [ + _make_invocation([ + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}}, + ]) + ] + expected = [ + _make_invocation([ + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}}, + {"name": "run_skill_script", "args": {"skill_name": "x"}}, + ]) + ] + result = tool_invocation_score(metric, actual, expected) + assert result.overall_score == 0.5 + assert result.overall_eval_status == EvalStatus.FAILED + + def test_extra_tools_are_ok(self): + metric = EvalMetric(metric_name="test") + actual = [ + _make_invocation([ + {"name": "list_skills"}, + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}}, + {"name": "execute_sql", "args": {"project_id": "x"}}, + ]) + ] + expected = [ + _make_invocation([ + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}}, + ]) + ] + result = tool_invocation_score(metric, actual, expected) + assert result.overall_score == 1.0 + + def test_empty_expected(self): + metric = EvalMetric(metric_name="test") + result = tool_invocation_score(metric, [], None) + assert result.overall_score == 1.0 + + +# ── tool_args_score tests ───────────────────────────────────────── + + +class TestToolArgsScore: + + def test_all_args_match(self): + metric = EvalMetric(metric_name="test") + actual = [ + _make_invocation([ + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}}, + { + "name": "load_skill_resource", + "args": { + "skill_name": "bq-sql-analyst", + "path": "references/public-datasets.md", + }, + }, + ]) + ] + expected = [ + _make_invocation([ + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}}, + { + "name": "load_skill_resource", + "args": { + "skill_name": "bq-sql-analyst", + "path": "references/public-datasets.md", + }, + }, + ]) + ] + result = tool_args_score(metric, actual, expected) + assert result.overall_score == 1.0 + + def test_wrong_skill_name(self): + metric = EvalMetric(metric_name="test") + actual = [ + _make_invocation([ + {"name": "load_skill", "args": {"name": "wrong-skill"}}, + ]) + ] + expected = [ + _make_invocation([ + {"name": "load_skill", "args": {"name": "bq-sql-analyst"}}, + ]) + ] + result = tool_args_score(metric, actual, expected) + assert result.overall_score == 0.0 + + def test_wrong_path(self): + metric = EvalMetric(metric_name="test") + actual = [ + _make_invocation([ + { + "name": "load_skill_resource", + "args": { + "skill_name": "bq-sql-analyst", + "path": "references/wrong.md", + }, + }, + ]) + ] + expected = [ + _make_invocation([ + { + "name": "load_skill_resource", + "args": { + "skill_name": "bq-sql-analyst", + "path": "references/public-datasets.md", + }, + }, + ]) + ] + result = tool_args_score(metric, actual, expected) + # skill_name matches (1/2), path doesn't (0/2) -> 1/2 = 0.5 + assert result.overall_score == 0.5 + + def test_no_key_args_in_expected(self): + metric = EvalMetric(metric_name="test") + actual = [_make_invocation([{"name": "list_skills"}])] + expected = [_make_invocation([{"name": "list_skills"}])] + result = tool_args_score(metric, actual, expected) + assert result.overall_score == 1.0 + + +# ── instruction_adherence_score tests ───────────────────────────── + + +def _make_rubric(rubric_id: str, text: str) -> Rubric: + return Rubric( + rubric_id=rubric_id, + rubric_content=RubricContent(text_property=text), + ) + + +class TestInstructionAdherenceScore: + + @pytest.mark.asyncio + async def test_no_rubrics_returns_pass(self): + actual = [_make_invocation([{"name": "list_skills"}])] + result = await instruction_adherence_score(actual, None) + assert result.overall_score == 1.0 + assert result.overall_eval_status == EvalStatus.PASSED + + @pytest.mark.asyncio + async def test_all_rubrics_pass(self): + rubrics = [ + _make_rubric("r1", "The agent listed skills."), + _make_rubric("r2", "The response mentions bq-sql-analyst."), + ] + actual = [ + _make_invocation( + [{"name": "list_skills"}], + user_text="What skills are available?", + final_text="Available skills: bq-sql-analyst.", + ) + ] + + mock_response = mock.MagicMock() + mock_response.text = ( + "Property: The agent listed skills.\n" + "Rationale: The agent called list_skills.\n" + "Verdict: yes\n\n" + "Property: The response mentions bq-sql-analyst.\n" + "Rationale: The response explicitly names bq-sql-analyst.\n" + "Verdict: yes\n" + ) + + mock_models = mock.AsyncMock() + mock_models.generate_content.return_value = mock_response + mock_aio = mock.MagicMock() + mock_aio.models = mock_models + mock_client = mock.MagicMock() + mock_client.aio = mock_aio + + with mock.patch("google.genai.Client", return_value=mock_client): + result = await instruction_adherence_score(actual, rubrics) + + assert result.overall_score == 1.0 + assert result.overall_eval_status == EvalStatus.PASSED + + @pytest.mark.asyncio + async def test_some_rubrics_fail(self): + rubrics = [ + _make_rubric("r1", "The agent loaded the skill."), + _make_rubric("r2", "The result has a table."), + ] + actual = [ + _make_invocation( + [{"name": "load_skill", "args": {"name": "bq-sql-analyst"}}], + final_text="Skill loaded.", + ) + ] + + mock_response = mock.MagicMock() + mock_response.text = ( + "Property: The agent loaded the skill.\n" + "Rationale: load_skill was called.\n" + "Verdict: yes\n\n" + "Property: The result has a table.\n" + "Rationale: No table in the response.\n" + "Verdict: no\n" + ) + + mock_models = mock.AsyncMock() + mock_models.generate_content.return_value = mock_response + mock_aio = mock.MagicMock() + mock_aio.models = mock_models + mock_client = mock.MagicMock() + mock_client.aio = mock_aio + + with mock.patch("google.genai.Client", return_value=mock_client): + result = await instruction_adherence_score(actual, rubrics) + + assert result.overall_score == 0.5 + assert result.overall_eval_status == EvalStatus.FAILED + + @pytest.mark.asyncio + async def test_llm_call_failure(self): + rubrics = [_make_rubric("r1", "Some assertion.")] + actual = [_make_invocation([{"name": "list_skills"}])] + + with mock.patch("google.genai.Client", side_effect=Exception("API error")): + result = await instruction_adherence_score(actual, rubrics) + + assert result.overall_score == 0.0 + assert result.overall_eval_status == EvalStatus.FAILED + + +# ── eval JSON validation ────────────────────────────────────────── + + +class TestEvalSetValidation: + + def test_eval_json_parses(self): + import pathlib + + eval_path = ( + pathlib.Path(__file__).parent.parent.parent.parent.parent + / "benchmarks" + / "bigquerybench" + / "eval_sets" + / "bigquerybench_eval.json" + ) + with open(eval_path) as f: + data = json.load(f) + es = EvalSet.model_validate(data) + assert len(es.eval_cases) == 5 + + def test_all_cases_have_rubrics(self): + import pathlib + + eval_path = ( + pathlib.Path(__file__).parent.parent.parent.parent.parent + / "benchmarks" + / "bigquerybench" + / "eval_sets" + / "bigquerybench_eval.json" + ) + with open(eval_path) as f: + data = json.load(f) + es = EvalSet.model_validate(data) + for case in es.eval_cases: + assert case.rubrics is not None, f"{case.eval_id} missing rubrics" + assert len(case.rubrics) >= 2, f"{case.eval_id} should have >= 2 rubrics" diff --git a/tests/unittests/tools/test_skill_toolset.py b/tests/unittests/tools/test_skill_toolset.py index 066eedfb67..6532332435 100644 --- a/tests/unittests/tools/test_skill_toolset.py +++ b/tests/unittests/tools/test_skill_toolset.py @@ -12,8 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +# pylint: disable=redefined-outer-name,g-import-not-at-top,protected-access + + from unittest import mock +from google.adk.code_executors.base_code_executor import BaseCodeExecutor +from google.adk.code_executors.code_execution_utils import CodeExecutionResult from google.adk.models import llm_request as llm_request_model from google.adk.skills import models from google.adk.tools import skill_toolset @@ -27,6 +32,7 @@ def mock_skill1_frontmatter(): frontmatter = mock.create_autospec(models.Frontmatter, instance=True) frontmatter.name = "skill1" frontmatter.description = "Skill 1 description" + frontmatter.allowed_tools = ["test_tool"] frontmatter.model_dump.return_value = { "name": "skill1", "description": "Skill 1 description", @@ -43,7 +49,14 @@ def mock_skill1(mock_skill1_frontmatter): skill.instructions = "instructions for skill1" skill.frontmatter = mock_skill1_frontmatter skill.resources = mock.MagicMock( - spec=["get_reference", "get_asset", "get_script"] + spec=[ + "get_reference", + "get_asset", + "get_script", + "list_references", + "list_assets", + "list_scripts", + ] ) def get_ref(name): @@ -59,11 +72,22 @@ def get_asset(name): def get_script(name): if name == "setup.sh": return models.Script(src="echo setup") + if name == "run.py": + return models.Script(src="print('hello')") + if name == "build.rb": + return models.Script(src="puts 'hello'") return None skill.resources.get_reference.side_effect = get_ref skill.resources.get_asset.side_effect = get_asset skill.resources.get_script.side_effect = get_script + skill.resources.list_references.return_value = ["ref1.md"] + skill.resources.list_assets.return_value = ["asset1.txt"] + skill.resources.list_scripts.return_value = [ + "setup.sh", + "run.py", + "build.rb", + ] return skill @@ -73,6 +97,7 @@ def mock_skill2_frontmatter(): frontmatter = mock.create_autospec(models.Frontmatter, instance=True) frontmatter.name = "skill2" frontmatter.description = "Skill 2 description" + frontmatter.allowed_tools = [] frontmatter.model_dump.return_value = { "name": "skill2", "description": "Skill 2 description", @@ -89,7 +114,14 @@ def mock_skill2(mock_skill2_frontmatter): skill.instructions = "instructions for skill2" skill.frontmatter = mock_skill2_frontmatter skill.resources = mock.MagicMock( - spec=["get_reference", "get_asset", "get_script"] + spec=[ + "get_reference", + "get_asset", + "get_script", + "list_references", + "list_assets", + "list_scripts", + ] ) def get_ref(name): @@ -104,6 +136,9 @@ def get_asset(name): skill.resources.get_reference.side_effect = get_ref skill.resources.get_asset.side_effect = get_asset + skill.resources.list_references.return_value = ["ref2.md"] + skill.resources.list_assets.return_value = ["asset2.txt"] + skill.resources.list_scripts.return_value = [] return skill @@ -132,13 +167,13 @@ def test_list_skills(mock_skill1, mock_skill2): async def test_get_tools(mock_skill1, mock_skill2): toolset = skill_toolset.SkillToolset([mock_skill1, mock_skill2]) tools = await toolset.get_tools() - assert len(tools) == 3 + assert len(tools) == 4 assert isinstance(tools[0], skill_toolset.ListSkillsTool) assert isinstance(tools[1], skill_toolset.LoadSkillTool) assert isinstance(tools[2], skill_toolset.LoadSkillResourceTool) + assert isinstance(tools[3], skill_toolset.RunSkillScriptTool) -@pytest.mark.asyncio @pytest.mark.asyncio async def test_list_skills_tool( mock_skill1, mock_skill2, tool_context_instance @@ -308,3 +343,854 @@ async def test_scripts_resource_not_found(mock_skill1, tool_context_instance): tool_context=tool_context_instance, ) assert result["error_code"] == "RESOURCE_NOT_FOUND" + + +# RunSkillScriptTool tests + + +def _make_tool_context_with_agent(agent=None): + """Creates a mock ToolContext with _invocation_context.agent.""" + ctx = mock.MagicMock(spec=tool_context.ToolContext) + ctx._invocation_context = mock.MagicMock() + ctx._invocation_context.agent = agent or mock.MagicMock() + return ctx + + +def _make_mock_executor(stdout="", stderr=""): + """Creates a mock code executor that returns the given output.""" + executor = mock.create_autospec(BaseCodeExecutor, instance=True) + executor.execute_code.return_value = CodeExecutionResult( + stdout=stdout, stderr=stderr + ) + return executor + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "args, expected_error_code", + [ + ( + {"script_path": "setup.sh"}, + "MISSING_SKILL_NAME", + ), + ( + {"skill_name": "skill1"}, + "MISSING_SCRIPT_PATH", + ), + ( + {"skill_name": "", "script_path": "setup.sh"}, + "MISSING_SKILL_NAME", + ), + ( + {"skill_name": "skill1", "script_path": ""}, + "MISSING_SCRIPT_PATH", + ), + ], +) +async def test_execute_script_missing_params( + mock_skill1, args, expected_error_code +): + executor = _make_mock_executor() + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async(args=args, tool_context=ctx) + assert result["error_code"] == expected_error_code + + +@pytest.mark.asyncio +async def test_execute_script_skill_not_found(mock_skill1): + executor = _make_mock_executor() + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "nonexistent", "script_path": "setup.sh"}, + tool_context=ctx, + ) + assert result["error_code"] == "SKILL_NOT_FOUND" + + +@pytest.mark.asyncio +async def test_execute_script_script_not_found(mock_skill1): + executor = _make_mock_executor() + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "nonexistent.py"}, + tool_context=ctx, + ) + assert result["error_code"] == "SCRIPT_NOT_FOUND" + + +@pytest.mark.asyncio +async def test_execute_script_no_code_executor(mock_skill1): + toolset = skill_toolset.SkillToolset([mock_skill1]) + tool = skill_toolset.RunSkillScriptTool(toolset) + # Agent without code_executor attribute + agent = mock.MagicMock(spec=[]) + ctx = _make_tool_context_with_agent(agent=agent) + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "setup.sh"}, + tool_context=ctx, + ) + assert result["error_code"] == "NO_CODE_EXECUTOR" + + +@pytest.mark.asyncio +async def test_execute_script_agent_code_executor_none(mock_skill1): + """Agent has code_executor attr but it's None.""" + toolset = skill_toolset.SkillToolset([mock_skill1]) + tool = skill_toolset.RunSkillScriptTool(toolset) + agent = mock.MagicMock() + agent.code_executor = None + ctx = _make_tool_context_with_agent(agent=agent) + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "setup.sh"}, + tool_context=ctx, + ) + assert result["error_code"] == "NO_CODE_EXECUTOR" + + +@pytest.mark.asyncio +async def test_execute_script_unsupported_type(mock_skill1): + executor = _make_mock_executor() + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "build.rb"}, + tool_context=ctx, + ) + assert result["error_code"] == "UNSUPPORTED_SCRIPT_TYPE" + + +@pytest.mark.asyncio +async def test_execute_script_python_success(mock_skill1): + executor = _make_mock_executor(stdout="hello\n") + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "run.py"}, + tool_context=ctx, + ) + assert result["status"] == "success" + assert result["stdout"] == "hello\n" + assert result["stderr"] == "" + assert result["skill_name"] == "skill1" + assert result["script_path"] == "run.py" + + # Verify the code passed to executor runs the python scripts + call_args = executor.execute_code.call_args + code_input = call_args[0][1] + assert "_materialize_and_run()" in code_input.code + assert "import runpy" in code_input.code + assert "sys.argv = ['scripts/run.py']" in code_input.code + assert ( + "runpy.run_path('scripts/run.py', run_name='__main__')" in code_input.code + ) + + +@pytest.mark.asyncio +async def test_execute_script_shell_success(mock_skill1): + executor = _make_mock_executor(stdout="setup\n") + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "setup.sh"}, + tool_context=ctx, + ) + assert result["status"] == "success" + assert result["stdout"] == "setup\n" + + # Verify the code wraps in subprocess.run with JSON envelope + call_args = executor.execute_code.call_args + code_input = call_args[0][1] + assert "subprocess.run" in code_input.code + assert "bash" in code_input.code + assert "__shell_result__" in code_input.code + + +@pytest.mark.asyncio +async def test_execute_script_with_input_args_python(mock_skill1): + executor = _make_mock_executor(stdout="done\n") + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={ + "skill_name": "skill1", + "script_path": "run.py", + "args": {"verbose": True, "count": "3"}, + }, + tool_context=ctx, + ) + assert result["status"] == "success" + + call_args = executor.execute_code.call_args + code_input = call_args[0][1] + assert ( + "['scripts/run.py', '--verbose', 'True', '--count', '3']" + in code_input.code + ) + + +@pytest.mark.asyncio +async def test_execute_script_with_input_args_shell(mock_skill1): + executor = _make_mock_executor(stdout="done\n") + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={ + "skill_name": "skill1", + "script_path": "setup.sh", + "args": {"force": True}, + }, + tool_context=ctx, + ) + assert result["status"] == "success" + + call_args = executor.execute_code.call_args + code_input = call_args[0][1] + assert "['bash', 'scripts/setup.sh', '--force', 'True']" in code_input.code + + +@pytest.mark.asyncio +async def test_execute_script_scripts_prefix_stripping(mock_skill1): + executor = _make_mock_executor(stdout="setup\n") + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={ + "skill_name": "skill1", + "script_path": "scripts/setup.sh", + }, + tool_context=ctx, + ) + assert result["status"] == "success" + assert result["script_path"] == "scripts/setup.sh" + + +@pytest.mark.asyncio +async def test_execute_script_toolset_executor_priority(mock_skill1): + """Toolset-level executor takes priority over agent's.""" + toolset_executor = _make_mock_executor(stdout="from toolset\n") + agent_executor = _make_mock_executor(stdout="from agent\n") + toolset = skill_toolset.SkillToolset( + [mock_skill1], code_executor=toolset_executor + ) + tool = skill_toolset.RunSkillScriptTool(toolset) + agent = mock.MagicMock() + agent.code_executor = agent_executor + ctx = _make_tool_context_with_agent(agent=agent) + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "run.py"}, + tool_context=ctx, + ) + assert result["stdout"] == "from toolset\n" + toolset_executor.execute_code.assert_called_once() + agent_executor.execute_code.assert_not_called() + + +@pytest.mark.asyncio +async def test_execute_script_agent_executor_fallback(mock_skill1): + """Falls back to agent's code executor when toolset has none.""" + agent_executor = _make_mock_executor(stdout="from agent\n") + toolset = skill_toolset.SkillToolset([mock_skill1]) + tool = skill_toolset.RunSkillScriptTool(toolset) + agent = mock.MagicMock() + agent.code_executor = agent_executor + ctx = _make_tool_context_with_agent(agent=agent) + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "run.py"}, + tool_context=ctx, + ) + assert result["stdout"] == "from agent\n" + agent_executor.execute_code.assert_called_once() + + +@pytest.mark.asyncio +async def test_execute_script_execution_error(mock_skill1): + executor = _make_mock_executor() + executor.execute_code.side_effect = RuntimeError("boom") + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "run.py"}, + tool_context=ctx, + ) + assert result["error_code"] == "EXECUTION_ERROR" + assert "boom" in result["error"] + assert result["error"].startswith("Failed to execute script 'run.py':") + + +@pytest.mark.asyncio +async def test_execute_script_stderr_only_sets_error_status(mock_skill1): + """stderr with no stdout should report error status.""" + executor = _make_mock_executor(stdout="", stderr="fatal error\n") + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "run.py"}, + tool_context=ctx, + ) + assert result["status"] == "error" + assert result["stderr"] == "fatal error\n" + + +@pytest.mark.asyncio +async def test_execute_script_stderr_with_stdout_sets_warning(mock_skill1): + """stderr alongside stdout should report warning status.""" + executor = _make_mock_executor(stdout="output\n", stderr="deprecation\n") + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "run.py"}, + tool_context=ctx, + ) + assert result["status"] == "warning" + assert result["stdout"] == "output\n" + assert result["stderr"] == "deprecation\n" + + +@pytest.mark.asyncio +async def test_execute_script_execution_error_truncated(mock_skill1): + """Long exception messages are truncated to avoid wasting LLM tokens.""" + executor = _make_mock_executor() + executor.execute_code.side_effect = RuntimeError("x" * 300) + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "run.py"}, + tool_context=ctx, + ) + assert result["error_code"] == "EXECUTION_ERROR" + # 200 chars of the message + "..." suffix + the prefix + assert result["error"].endswith("...") + assert len(result["error"]) < 300 + + +@pytest.mark.asyncio +async def test_execute_script_system_exit_caught(mock_skill1): + """sys.exit() in a script should not terminate the process.""" + executor = _make_mock_executor() + executor.execute_code.side_effect = SystemExit(1) + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "run.py"}, + tool_context=ctx, + ) + assert result["error_code"] == "EXECUTION_ERROR" + assert "exited with code 1" in result["error"] + + +@pytest.mark.asyncio +async def test_execute_script_system_exit_zero_is_success(mock_skill1): + """sys.exit(0) is a normal termination and should report success.""" + executor = _make_mock_executor() + executor.execute_code.side_effect = SystemExit(0) + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "run.py"}, + tool_context=ctx, + ) + assert result["status"] == "success" + + +@pytest.mark.asyncio +async def test_execute_script_system_exit_none_is_success(mock_skill1): + """sys.exit() with no arg (None) should report success.""" + executor = _make_mock_executor() + executor.execute_code.side_effect = SystemExit(None) + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "run.py"}, + tool_context=ctx, + ) + assert result["status"] == "success" + + +@pytest.mark.asyncio +async def test_execute_script_shell_includes_timeout(mock_skill1): + """Shell wrapper includes timeout in subprocess.run.""" + executor = _make_mock_executor(stdout="ok\n") + toolset = skill_toolset.SkillToolset( + [mock_skill1], code_executor=executor, script_timeout=60 + ) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "setup.sh"}, + tool_context=ctx, + ) + assert result["status"] == "success" + call_args = executor.execute_code.call_args + code_input = call_args[0][1] + assert "timeout=60" in code_input.code + + +@pytest.mark.asyncio +async def test_execute_script_extensionless_unsupported(mock_skill1): + """Files without extensions should return UNSUPPORTED_SCRIPT_TYPE.""" + # Add a script with no extension to the mock + original_side_effect = mock_skill1.resources.get_script.side_effect + + def get_script_extended(name): + if name == "noext": + return models.Script(src="print('hi')") + return original_side_effect(name) + + mock_skill1.resources.get_script.side_effect = get_script_extended + + executor = _make_mock_executor() + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "noext"}, + tool_context=ctx, + ) + assert result["error_code"] == "UNSUPPORTED_SCRIPT_TYPE" + + +# ── Integration tests using real UnsafeLocalCodeExecutor ── + + +def _make_skill_with_script(skill_name, script_name, script): + """Creates a minimal mock Skill with a single script.""" + skill = mock.create_autospec(models.Skill, instance=True) + skill.name = skill_name + skill.description = f"Test skill {skill_name}" + skill.instructions = "test instructions" + fm = mock.create_autospec(models.Frontmatter, instance=True) + fm.name = skill_name + fm.description = f"Test skill {skill_name}" + skill.frontmatter = fm + skill.resources = mock.MagicMock( + spec=[ + "get_reference", + "get_asset", + "get_script", + "list_references", + "list_assets", + "list_scripts", + ] + ) + + def get_script(name): + if name == script_name: + return script + return None + + skill.resources.get_script.side_effect = get_script + skill.resources.get_reference.return_value = None + skill.resources.get_asset.return_value = None + skill.resources.list_references.return_value = [] + skill.resources.list_assets.return_value = [] + skill.resources.list_scripts.return_value = [script_name] + return skill + + +def _make_real_executor_toolset(skills, **kwargs): + """Creates a SkillToolset with a real UnsafeLocalCodeExecutor.""" + from google.adk.code_executors.unsafe_local_code_executor import UnsafeLocalCodeExecutor + + executor = UnsafeLocalCodeExecutor() + return skill_toolset.SkillToolset(skills, code_executor=executor, **kwargs) + + +@pytest.mark.asyncio +async def test_integration_python_stdout(): + """Real executor: Python script stdout is captured.""" + script = models.Script(src="print('hello world')") + skill = _make_skill_with_script("test_skill", "hello.py", script) + toolset = _make_real_executor_toolset([skill]) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={ + "skill_name": "test_skill", + "script_path": "hello.py", + }, + tool_context=ctx, + ) + assert result["status"] == "success" + assert result["stdout"] == "hello world\n" + assert result["stderr"] == "" + + +@pytest.mark.asyncio +async def test_integration_python_sys_exit_zero(): + """Real executor: sys.exit(0) is treated as success.""" + script = models.Script(src="import sys; sys.exit(0)") + skill = _make_skill_with_script("test_skill", "exit_zero.py", script) + toolset = _make_real_executor_toolset([skill]) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={ + "skill_name": "test_skill", + "script_path": "exit_zero.py", + }, + tool_context=ctx, + ) + assert result["status"] == "success" + + +@pytest.mark.asyncio +async def test_integration_shell_stdout_and_stderr(): + """Real executor: shell script preserves both stdout and stderr.""" + script = models.Script(src="echo output; echo warning >&2") + skill = _make_skill_with_script("test_skill", "both.sh", script) + toolset = _make_real_executor_toolset([skill]) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={ + "skill_name": "test_skill", + "script_path": "both.sh", + }, + tool_context=ctx, + ) + assert result["status"] == "warning" + assert "output" in result["stdout"] + assert "warning" in result["stderr"] + + +@pytest.mark.asyncio +async def test_integration_shell_stderr_only(): + """Real executor: shell script with only stderr reports error.""" + script = models.Script(src="echo failure >&2") + skill = _make_skill_with_script("test_skill", "err.sh", script) + toolset = _make_real_executor_toolset([skill]) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={ + "skill_name": "test_skill", + "script_path": "err.sh", + }, + tool_context=ctx, + ) + assert result["status"] == "error" + assert "failure" in result["stderr"] + + +# ── Shell JSON envelope parsing (unit tests with mock executor) ── + + +@pytest.mark.asyncio +async def test_shell_json_envelope_parsed(mock_skill1): + """Shell JSON envelope is correctly unpacked by run_async.""" + import json + + envelope = json.dumps({ + "__shell_result__": True, + "stdout": "hello from shell\n", + "stderr": "", + "returncode": 0, + }) + executor = _make_mock_executor(stdout=envelope) + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "setup.sh"}, + tool_context=ctx, + ) + assert result["status"] == "success" + assert result["stdout"] == "hello from shell\n" + assert result["stderr"] == "" + + +@pytest.mark.asyncio +async def test_shell_json_envelope_nonzero_returncode(mock_skill1): + """Non-zero returncode in shell envelope sets stderr.""" + import json + + envelope = json.dumps({ + "__shell_result__": True, + "stdout": "", + "stderr": "", + "returncode": 2, + }) + executor = _make_mock_executor(stdout=envelope) + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "setup.sh"}, + tool_context=ctx, + ) + assert result["status"] == "error" + assert "Exit code 2" in result["stderr"] + + +@pytest.mark.asyncio +async def test_shell_json_envelope_with_stderr(mock_skill1): + """Shell envelope with both stdout and stderr reports warning.""" + import json + + envelope = json.dumps({ + "__shell_result__": True, + "stdout": "data\n", + "stderr": "deprecation warning\n", + "returncode": 0, + }) + executor = _make_mock_executor(stdout=envelope) + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "setup.sh"}, + tool_context=ctx, + ) + assert result["status"] == "warning" + assert result["stdout"] == "data\n" + assert result["stderr"] == "deprecation warning\n" + + +@pytest.mark.asyncio +async def test_shell_json_envelope_timeout(mock_skill1): + """Shell envelope from TimeoutExpired reports error status.""" + import json + + envelope = json.dumps({ + "__shell_result__": True, + "stdout": "partial output\n", + "stderr": "Timed out after 300s", + "returncode": -1, + }) + executor = _make_mock_executor(stdout=envelope) + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "setup.sh"}, + tool_context=ctx, + ) + assert result["status"] == "error" + assert result["stdout"] == "partial output\n" + assert "Timed out" in result["stderr"] + + +@pytest.mark.asyncio +async def test_shell_non_json_stdout_passthrough(mock_skill1): + """Non-JSON shell stdout is passed through without parsing.""" + executor = _make_mock_executor(stdout="plain text output\n") + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={"skill_name": "skill1", "script_path": "setup.sh"}, + tool_context=ctx, + ) + assert result["status"] == "success" + assert result["stdout"] == "plain text output\n" + + +# ── input_files packaging ── + + +@pytest.mark.asyncio +async def test_execute_script_input_files_packaged(mock_skill1): + """Verify references, assets, and scripts are packaged inside the wrapper code.""" + executor = _make_mock_executor(stdout="ok\n") + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + await tool.run_async( + args={"skill_name": "skill1", "script_path": "run.py"}, + tool_context=ctx, + ) + + call_args = executor.execute_code.call_args + code_input = call_args[0][1] + + # input_files is no longer populated; it's serialized inside the script + assert code_input.input_files is None or len(code_input.input_files) == 0 + + # Ensure the extracted literal contains our fake files + assert "references/ref1.md" in code_input.code + assert "assets/asset1.txt" in code_input.code + assert "scripts/setup.sh" in code_input.code + assert "scripts/run.py" in code_input.code + assert "scripts/build.rb" in code_input.code + + # Verify content mappings exist in the string + assert "'references/ref1.md': 'ref content 1'" in code_input.code + assert "'assets/asset1.txt': 'asset content 1'" in code_input.code + + +# ── Integration: shell non-zero exit ── + + +@pytest.mark.asyncio +async def test_integration_shell_nonzero_exit(): + """Real executor: shell script with non-zero exit via JSON envelope.""" + script = models.Script(src="exit 42") + skill = _make_skill_with_script("test_skill", "fail.sh", script) + toolset = _make_real_executor_toolset([skill]) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={ + "skill_name": "test_skill", + "script_path": "fail.sh", + }, + tool_context=ctx, + ) + assert result["status"] == "error" + assert "42" in result["stderr"] + + +# ── Finding 1: system instruction references correct tool name ── + + +def test_system_instruction_references_run_skill_script(): + """System instruction must reference the actual tool name.""" + assert "run_skill_script" in skill_toolset.DEFAULT_SKILL_SYSTEM_INSTRUCTION + assert ( + "execute_skill_script" + not in skill_toolset.DEFAULT_SKILL_SYSTEM_INSTRUCTION + ) + + +# ── Finding 2: empty files are mounted (not silently dropped) ── + + +@pytest.mark.asyncio +async def test_execute_script_empty_files_mounted(): + """Verify empty files are included in wrapper code, not dropped.""" + skill = mock.create_autospec(models.Skill, instance=True) + skill.name = "skill_empty" + skill.resources = mock.MagicMock( + spec=[ + "get_reference", + "get_asset", + "get_script", + "list_references", + "list_assets", + "list_scripts", + ] + ) + skill.resources.get_reference.side_effect = ( + lambda n: "" if n == "empty.md" else None + ) + skill.resources.get_asset.side_effect = ( + lambda n: "" if n == "empty.cfg" else None + ) + skill.resources.get_script.side_effect = ( + lambda n: models.Script(src="") if n == "run.py" else None + ) + skill.resources.list_references.return_value = ["empty.md"] + skill.resources.list_assets.return_value = ["empty.cfg"] + skill.resources.list_scripts.return_value = ["run.py"] + + executor = _make_mock_executor(stdout="ok\n") + toolset = skill_toolset.SkillToolset([skill], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + await tool.run_async( + args={"skill_name": "skill_empty", "script_path": "run.py"}, + tool_context=ctx, + ) + + call_args = executor.execute_code.call_args + code_input = call_args[0][1] + assert "'references/empty.md': ''" in code_input.code + assert "'assets/empty.cfg': ''" in code_input.code + assert "'scripts/run.py': ''" in code_input.code + + +# ── Finding 3: invalid args type returns clear error ── + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "bad_args", + [ + "not a dict", + ["a", "list"], + 42, + True, + ], +) +async def test_execute_script_invalid_args_type(mock_skill1, bad_args): + """Non-dict args should return INVALID_ARGS_TYPE, not crash.""" + executor = _make_mock_executor() + toolset = skill_toolset.SkillToolset([mock_skill1], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + result = await tool.run_async( + args={ + "skill_name": "skill1", + "script_path": "run.py", + "args": bad_args, + }, + tool_context=ctx, + ) + assert result["error_code"] == "INVALID_ARGS_TYPE" + executor.execute_code.assert_not_called() + + +# ── Finding 4: binary file content is handled in wrapper ── + + +@pytest.mark.asyncio +async def test_execute_script_binary_content_packaged(): + """Verify binary asset content uses 'wb' mode in wrapper code.""" + skill = mock.create_autospec(models.Skill, instance=True) + skill.name = "skill_bin" + skill.resources = mock.MagicMock( + spec=[ + "get_reference", + "get_asset", + "get_script", + "list_references", + "list_assets", + "list_scripts", + ] + ) + skill.resources.get_reference.side_effect = ( + lambda n: b"\x00\x01\x02" if n == "data.bin" else None + ) + skill.resources.get_asset.return_value = None + skill.resources.get_script.side_effect = lambda n: ( + models.Script(src="print('ok')") if n == "run.py" else None + ) + skill.resources.list_references.return_value = ["data.bin"] + skill.resources.list_assets.return_value = [] + skill.resources.list_scripts.return_value = ["run.py"] + + executor = _make_mock_executor(stdout="ok\n") + toolset = skill_toolset.SkillToolset([skill], code_executor=executor) + tool = skill_toolset.RunSkillScriptTool(toolset) + ctx = _make_tool_context_with_agent() + await tool.run_async( + args={"skill_name": "skill_bin", "script_path": "run.py"}, + tool_context=ctx, + ) + + call_args = executor.execute_code.call_args + code_input = call_args[0][1] + # Binary content should appear as bytes literal + assert "b'\\x00\\x01\\x02'" in code_input.code + # Wrapper code handles binary with 'wb' mode + assert "'wb' if isinstance(content, bytes)" in code_input.code