Skip to Content

Tools & MCP Integration

The Agent SDK integrates with the Model Context Protocol (MCP) to provide access to a wide range of tools.

Overview

Tools enable agents to:

  • Search the web
  • Read and write files
  • Execute code
  • Interact with APIs
  • Access databases
  • And much more…

Idempotency Tokens

Tool calls that are replayed during checkpoint resume (e.g., after a crash) would normally execute twice, causing duplicate side effects — sending an email again, writing a record twice, charging a customer a second time.

Idempotency tokens prevent this. Each tool call is assigned a SHA-256 hash of its tool_call_id + arguments. The hash is stored in Redis with a TTL. If the same hash is seen again within the TTL window, the tool’s cached result is returned immediately without re-executing.

How It Works

Tool call received │ ▼ Compute SHA-256(tool_call_id + args) │ ├── Key exists in Redis → return cached result (no re-execution) │ ▼ Execute tool │ ▼ Store result in Redis (key: aix:idempotency:{hash}, TTL: idempotency_ttl_secs)

Configuration

Idempotency tokens are enabled by default when REDIS_URL is configured:

TOOL_IDEMPOTENCY_ENABLED=true # Enable idempotency (default: true) TOOL_IDEMPOTENCY_TTL_SECS=3600 # Cache window in seconds (default: 3600 = 1 hour)

Opting Out Per Tool

For tools where re-execution is safe (e.g., pure read operations), you can disable idempotency:

from agent_sdk import query, AgentOptions options = AgentOptions( idempotency_exempt_tools=["web_search", "read_file"] # Always re-execute these )

Redis Key Format

aix:idempotency:{sha256_hash}

The value is the serialized tool result. Key expires after TOOL_IDEMPOTENCY_TTL_SECS.

Note: Idempotency tokens protect against double-execution during checkpoint replay. They do not prevent a user from explicitly calling the same tool twice with the same arguments — only automatic replays are de-duplicated.

Tool Discovery

List Available Tools

from agent_sdk import get_available_tools # Get all available tools tools = await get_available_tools() for tool in tools[:10]: print(f"- {tool['name']}: {tool['description']}")

Find tools relevant to a specific task:

# Find tools for web research web_tools = await get_available_tools( user_query="I need to search the web and fetch URLs", max_results=5 ) # Find tools for file operations file_tools = await get_available_tools( user_query="read and write files", max_results=5 )

Tool Configuration

Explicit Tool List

Specify exactly which tools to allow:

from agent_sdk import query, AgentOptions options = AgentOptions( allowed_tools=[ "web_search", "fetch_url", "read_file", "write_file" ] ) async for msg in query("Research Python best practices", options=options): print(msg.content, end="" if msg.is_text else "\n")

Tool Discovery Modes

from agent_sdk import ToolDiscoveryMode # Explicit only - use only allowed_tools options = AgentOptions( tool_discovery=ToolDiscoveryMode.EXPLICIT, allowed_tools=["web_search", "read_file"] ) # Semantic - auto-discover based on query options = AgentOptions( tool_discovery=ToolDiscoveryMode.SEMANTIC ) # Hybrid - combine explicit list with semantic discovery options = AgentOptions( tool_discovery=ToolDiscoveryMode.HYBRID, allowed_tools=["read_file", "write_file"] # Always available )

Direct Tool Execution

For the hosted MCP gateway, configure the base URL without a /mcp suffix and use a dedicated request-local key:

export AIX_MCP_URL=https://aix.snnc.cc export AIX_MCP_API_KEY='isa_...'

For aix.snnc.cc, AIX_MCP_API_KEY takes precedence over the general AIX_API_KEY, while a verified request bearer takes precedence over both. Bearer and general platform credentials are never forwarded to custom MCP origins. To authenticate a custom origin, set AIX_MCP_API_KEY explicitly. Credential-bearing non-loopback MCP URLs must use HTTPS. MCP_SERVER_URL remains a legacy, lower-priority alias for AIX_MCP_URL.

Execute a Single Tool

from agent_sdk import execute_tool # Web search result = await execute_tool( tool_name="web_search", tool_args={"query": "Python async programming"}, session_id="my-session" ) print(result.content) # Read file result = await execute_tool( tool_name="read_file", tool_args={"path": "/path/to/file.txt"} ) # Execute bash command result = await execute_tool( tool_name="bash", tool_args={"command": "ls -la"} )

For identity-scoped tools, pass the authenticated principal through execute_tool(user_id=...). An organization API key authenticates as its organization and cannot impersonate an arbitrary child or synthetic user.

Handle Tool Results

result = await execute_tool("web_search", {"query": "test"}) if result.is_tool_result: if result.tool_error: print(f"Tool failed: {result.tool_error}") else: print(f"Result: {result.tool_result_value}")

MCP Server Configuration

Built-in MCP Server

The SDK connects to isA_MCP by default:

options = AgentOptions( # isA_MCP is used automatically # URL configured via AIX_MCP_URL environment variable )

External MCP Servers

Connect to additional MCP servers:

from agent_sdk import AgentOptions, MCPServerConfig options = AgentOptions( mcp_servers={ # GitHub MCP server "github": MCPServerConfig( command="npx", args=["-y", "@modelcontextprotocol/server-github"], env={"GITHUB_TOKEN": "your-token"} ), # Filesystem MCP server "filesystem": MCPServerConfig( command="npx", args=["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"] ), # Custom HTTP MCP server "custom": MCPServerConfig( url="http://localhost:9000/mcp" ), # Docker-based MCP server "docker-mcp": MCPServerConfig( command="docker", args=["run", "-i", "my-mcp-server"] ) } )

MCPServerConfig Options

MCPServerConfig( # For stdio-based servers command="npx", # Command to run args=["server-name"], # Arguments env={"KEY": "value"}, # Environment variables # For HTTP-based servers url="http://host:port/mcp" )

Tool Categories

Web Tools

# Search await execute_tool("web_search", {"query": "search terms"}) # Fetch URL content await execute_tool("fetch_url", {"url": "https://example.com"}) # Crawl website await execute_tool("web_crawl", {"url": "https://example.com", "depth": 2})

File Tools

# Read file await execute_tool("read_file", {"path": "/path/to/file"}) # Write file await execute_tool("write_file", { "path": "/path/to/file", "content": "file content" }) # List directory await execute_tool("list_directory", {"path": "/path/to/dir"}) # Delete file await execute_tool("delete_file", {"path": "/path/to/file"})

Code Execution Tools

# Bash command await execute_tool("bash", {"command": "echo hello"}) # Python execution await execute_tool("python_exec", {"code": "print(2+2)"})

Database Tools

# SQL query await execute_tool("database_query", { "connection": "postgresql://...", "query": "SELECT * FROM users LIMIT 10" })

Time Tools

# Get current time result = await execute_tool("get_current_time", {}) # Returns: {"iso": "2024-01-15T10:30:00Z", "date": "2024-01-15", ...} # Get current date result = await execute_tool("get_current_date", {})

Tool Execution in Streaming

Monitor Tool Usage

from agent_sdk import query tools_used = [] async for msg in query("Analyze the project structure"): if msg.is_tool_use: print(f"[Tool] {msg.tool_name}({msg.tool_args})") tools_used.append(msg.tool_name) elif msg.is_tool_result: if msg.tool_error: print(f"[Error] {msg.tool_error}") else: print(f"[Result] {str(msg.tool_result_value)[:100]}...") elif msg.is_text: print(msg.content, end="") print(f"\n\nTools used: {tools_used}")

Tool Execution with Progress

async for msg in query("Search multiple sources and compile results"): match msg.type: case "tool_use": print(f"Starting: {msg.tool_name}") case "tool_result": status = "failed" if msg.tool_error else "completed" print(f"Tool {status}: {msg.tool_name}") case "progress": print(f"Progress: {msg.progress_percent}%") case "text": print(msg.content, end="")

Tool Profiling

The SDK tracks tool execution times for optimization:

from agent_sdk.services.auto_detection import get_tool_profiler profiler = await get_tool_profiler() # Record custom execution await profiler.record_execution( tool_name="my_tool", execution_time_ms=1500, tool_args={"param": "value"}, session_id="session-123", success=True ) # Get execution estimate estimate = await profiler.estimate_time("web_search", {"query": "test"}) print(f"Estimated time: {estimate}ms") # Get statistics stats = await profiler.get_statistics("web_search") print(f"Average: {stats['avg_time_ms']}ms") print(f"P90: {stats['p90_time_ms']}ms")

Error Handling

Handle Tool Errors

from agent_sdk import execute_tool result = await execute_tool("web_search", {"query": "test"}) if result.tool_error: error_type = result.metadata.get("error_type", "unknown") match error_type: case "timeout": print("Tool timed out, retrying...") case "rate_limit": print("Rate limited, waiting...") case "not_found": print("Tool not found") case _: print(f"Error: {result.tool_error}")

Retry Logic

import asyncio async def execute_with_retry(tool_name, args, max_retries=3): for attempt in range(max_retries): result = await execute_tool(tool_name, args) if not result.tool_error: return result if "rate_limit" in str(result.tool_error): await asyncio.sleep(2 ** attempt) else: break return result

ToolPolicy Governance & Manifest Contracts

In enterprise deployments, tool access is governed by the versioned ToolPolicy component inside the agent’s HarnessManifest.

Dynamic Weights vs. Structural Invariants

  • ToolRLWeights (Dynamic Steering): Runtime weights for tool selection, correctness, and efficiency that guide exploration/exploitation during step execution.
  • ToolPolicy (Structural Invariants): Hard constraints compiled into the signed HarnessManifest. These prevent tool hallucinations, enforce strict argument type schemas, and mandate prerequisite calling sequences regardless of prompt variations.

Policy Structure

{ "kind": "tool_policy", "version": "1.1.0", "artifact_ref": "policy://crm-tools-v1", "content_hash": "sha256:7b53a...", "constraints": { "required_prerequisites": { "delete_customer": ["verify_customer_identity", "get_customer_balance"] }, "banned_combinations": [ ["grant_admin", "revoke_audit_log"] ], "argument_bounds": { "query_limit": {"max": 100, "min": 1} } } }

Manifest Verification

Tool policies cannot be modified on the fly without an approved and signed HarnessManifestEnvelope:

python -m isa_agent_sdk.cli verify-harness-manifest \ --envelope promoted-harness.json \ --trust-policy /run/secrets/harness-trust-roots.json

Diagnostic Tools

To support autonomous incident triage and root cause analysis across telemetry fabrics and knowledge graphs, the Agent SDK provides high-performance, strictly governed diagnostic tools under isa_agent_sdk.tools.diagnostics.

DuckDB Analytical Pushdown

The duckdb_telemetry_query diagnostic tool (DuckDBDiagnosticTool) enables agents to execute zero-copy in-process analytical SQL queries directly over Snappy-compressed Parquet lake partitions stored in S3 or MinIO object storage.

Zero-Copy Analytical Pushdown Architecture

By leveraging DuckDB’s httpfs extension with vectorized projection and predicate pushdown, agents can query billions of telemetry spans without transferring entire Parquet files over the network or allocating large in-memory data frames.

Security Governance & Read-Only Invariants

To prevent prompt-injection attacks and inadvertent mutations during diagnosis, duckdb_telemetry_query executes strict AST and lexical validation via validate_readonly_sql:

  • Single Statement Enforcement: Multi-statement execution via semicolons is blocked to eliminate SQL injection chaining.
  • Allowed Starting Keywords: Queries must strictly begin with one of: SELECT, WITH, DESCRIBE, EXPLAIN, SUMMARIZE, SHOW.
  • Blocked Mutation Keywords: Keywords like DROP, INSERT, UPDATE, ALTER, DELETE, TRUNCATE, ATTACH, DETACH, COPY, EXPORT, IMPORT, INSTALL, LOAD, PRAGMA, CALL, SET, RESET, CREATE, and REPLACE raise immediate validation errors.
  • Blocked File System Functions: Direct local file system reads (READ_CSV, READ_TEXT, READ_BLOB, READ_JSON, GLOB, path traversals /etc, ../) are rejected.
  • Credential Protection: Calls inspecting internal credentials (such as current_setting('s3_secret_access_key')) are detected and blocked.

Input Schema & Parameters

ParameterTypeRequiredDefaultDescription
querystringYes—Analytical read-only SQL query
minio_endpointstringNoMINIO_ENDPOINT or localhost:9000S3/MinIO endpoint override
bucketstringNoisa-data-lakeTarget telemetry bucket
access_keystringNoMINIO_ACCESS_KEYStorage access key
secret_keystringNoMINIO_SECRET_KEYStorage secret key
securebooleanNofalseEnable TLS/SSL connection
connectionAnyNoNonePre-configured DuckDB connection

Execution Flow & Output Schema

The tool executes asynchronously in a worker thread (asyncio.to_thread) to prevent blocking the agent runtime event loop. It returns a structured response dictionary:

{ "success": true, "columns": ["run_id", "name", "duration_ms", "status", "error"], "rows": [ { "run_id": "run:9f8e21a0-43b2-4cd8-8610-d88192801124", "name": "AEP_Quota_Evaluator", "duration_ms": 3410, "status": "FAILED", "error": "ConnectionTimeout: upstream token vault unreachable" } ], "results": [ /* mirrored rows */ ], "row_count": 1, "query": "SELECT run_id, name, duration_ms, status, error FROM read_parquet('s3://isa-data-lake/lake/telemetry/spans/year=2026/month=11/*/*.parquet') WHERE status = 'FAILED' LIMIT 10" }

Usage Example

from isa_agent_sdk.tools.diagnostics import duckdb_telemetry_query # Query recent span failures from the Parquet lake result = await duckdb_telemetry_query( query=""" SELECT run_id, name, model, duration_ms, error FROM read_parquet('s3://isa-data-lake/lake/telemetry/spans/year=2026/month=11/*/*.parquet') WHERE status = 'FAILED' ORDER BY start_time DESC LIMIT 5 """ ) if result["success"]: print(f"Discovered {result['row_count']} failed runs:") for row in result["rows"]: print(f"- {row['name']} ({row['run_id']}): {row['error']}")

Cypher Graph Traversal

The cypher_causality_traversal diagnostic tool (CypherDiagnosticTool) enables agents to navigate causal dependency graphs across execution :Run nodes and :DataAsset nodes stored in the platform graph plane (FalkorDB / Neo4j / NebulaGraph).

Causal Graph Traversal Architecture

Security Governance & Query Complexity Constraints

To protect graph database stability and block malicious prompt injections, cypher_causality_traversal validates all queries via validate_readonly_cypher:

  • Read-Only Start Keywords: Queries must strictly begin with MATCH, OPTIONAL, WITH, RETURN, UNWIND, EXPLAIN, or PROFILE.
  • Blocked Mutating Clauses: Clauses like CREATE, MERGE, DELETE, SET, REMOVE, DROP, DETACH, ERASE, FOREACH, APOC, LOAD, CALL, and PROCEDURE are prohibited.
  • Cartesian Product Limits: Unconstrained cartesian products (4 or more disconnected MATCH patterns) are blocked to prevent combinatorial explosion.
  • Path Length Safety Caps: Unbounded variable-length traversals (e.g. [*], [*..], [*1..]) are strictly forbidden. The maximum variable length path traversal depth is hard-capped at 10 hops (e.g. *1..10).

Input Schema & Parameters

ParameterTypeRequiredDefaultDescription
querystringYes—Read-only Cypher causality query
parametersdictNo{}Parameter substitutions dictionary
graph_serviceAnyNoNonePolymorphic graph service / client instance

Polymorphic Graph Dispatch

The tool seamlessly dispatches queries across multiple platform graph layers:

  1. GraphService.run_cypher(query, parameters)
  2. GraphClient.query(query, params, write=False)
  3. MetadataGraphService._run(query, params, write=False)
  4. Direct callable functions or mock handlers for testing.

Canonical Lineage Queries

1. Upstream Blast Radius & Causal Origin

Discover the root run that produced a corrupted data asset:

MATCH path = (asset:DataAsset {id: $asset_id})-[:PRODUCED_BY]->(r:Run) OPTIONAL MATCH (r)-[:CAUSED_BY*1..5]->(root:Run) RETURN r.id AS direct_run, r.name AS step_name, root.id AS root_cause_run, length(path) AS depth
2. Downstream Impact Analysis

Identify all downstream consumer runs and derived data assets affected by a failed run:

MATCH (failed:Run {id: $failed_run_id})<-[:PRODUCED_BY]-(asset:DataAsset)-[:CONSUMED_BY]->(downstream:Run) RETURN asset.id AS affected_asset, downstream.id AS impacted_run, downstream.status AS downstream_status

Usage Example

from isa_agent_sdk.tools.diagnostics import cypher_causality_traversal # Trace causal dependencies for an anomalous data asset res = await cypher_causality_traversal( query=""" MATCH (a:DataAsset {id: $asset_id})-[:PRODUCED_BY]->(r:Run) OPTIONAL MATCH (r)-[:CAUSED_BY*1..3]->(upstream:Run) RETURN a.id AS asset, r.id AS producer_run, r.status AS status, upstream.id AS upstream_cause """, parameters={"asset_id": "data_asset:agent_assets/orders_v2"} ) if res["success"]: for record in res["results"]: print(f"Asset {record['asset']} was produced by run {record['producer_run']} (status: {record['status']})")

Best Practices

  1. Use explicit tool lists for production - More predictable behavior
  2. Handle tool errors - Always check for failures
  3. Monitor tool usage - Track which tools are being used
  4. Set appropriate timeouts - Prevent hanging operations
  5. Use semantic discovery for exploration - Let the agent find relevant tools

Next Steps

Was this page helpful?