Production-grade guide to agent tool creation covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Agent tool creation is the process of defining, packaging, and exposing external capabilities so that an AI agent can invoke them at runtime. It matters whenever an agent’s built-in operations don’t cover the needed domain—such as querying a private database, interacting with a legacy API, or performing file transformations that aren’t represented in the agent’s core toolset. This page walks through the practical steps of bringing a new tool into an agent workflow, from writing the executable interface to registering it with the runtime, passing inputs, capturing outputs, and troubleshooting the common failure modes that appear after deployment.
Most agent runtimes expect a tool to conform to a simple input/output contract: the runtime supplies a JSON payload (either via environment variable or stdin), the tool performs work, and it writes a JSON response to stdout before exiting with code 0. Any non-zero exit code is treated as failure, and any stdout that isn’t valid JSON is typically dropped or flagged as a parse error.
A minimal Python script that respects this contract might look like this:
#!/usr/bin/env python3
import sys, json, os
def main():
try:
payload_str = os.environ.get("TOOL_INPUT", "{}")
payload = json.loads(payload_str)
except json.JSONDecodeError:
print(json.dumps({"error": "invalid TOOL_INPUT environment variable"}), file=sys.stderr)
sys.exit(2)
# --- tool logic goes here ---
# Example: coerce inputs, call an external service, compute a result
result = {
"status": "ok",
"received_id": payload.get("id"),
"reply": "acknowledged"
}
# ---------------------------------
print(json.dumps(result))
sys.exit(0)
if __name__ == "__main__":
main()
Make the script executable (chmod +x tool.py) and place it in a context the runtime can discover—often a directory mounted into a container, a path listed in the agent’s tool manifest, or a git-tracked binary.
Containerizing the tool is the most portable way to guarantee the runtime sees the exact interpreter and package set you tested with:
docker build -t my-tool:latest .
The resulting image can be run directly for ad‑hoc testing:
docker run -e TOOL_INPUT='{"id":"req-42"}' my-tool:latest
If the agent runtime exposes a remote endpoint, you can invoke the container through a local proxy, but the boundary between “local execution” and “remote invocation” is defined by the contract, not the transport.
Once the executable exists, the runtime needs to know its name, expected schema, entrypoint, and resource limits. Many frameworks represent this as a plain‑JSON or YAML manifest that the agent reads on startup. The shape is usually a small object with keys like name, description, parameters (an object describing required/optional fields and their types), and command (the executable path or container image reference).
A concrete example of a manifest fragment, written in JSON:
{
"name": "csv_to_json",
"description": "Reads a CSV string from TOOL_INPUT and returns parsed JSON rows.",
"parameters": {
"type": "object",
"properties": {
"csv": {
"type": "string",
"description": "Raw CSV text, first row assumed to be headers."
}
},
"required": ["csv"],
"additionalProperties": false
},
"command": "python3 /tool.py",
"timeout_seconds": 30,
"env": {
"TOOL_INPUT": ""
}
}
To register this with a generic agent runtime reachable over HTTP, you might use curl:
curl -s -X POST http://agent-local:8080/v1/tools \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AGENT_TOKEN" \
-d @csv_to_json.json
The exact path (/v1/tools) and auth mechanism depend on the specific runtime, but the pattern—POST with a JSON body containing at minimum a name and command—is nearly universal. After a successful request, the runtime typically responds with the tool’s registered ID and a short description of its validated schema.
If you are using a framework that stores tool definitions in git, you can add the manifest to version control and let the agent operator reconcile it:
git add csv_to_json.json
git commit -m "add csv_to_json tool definition"
git push origin main
The operator’s reconciliation loop then reads the new manifest and makes the tool available to running agents without a restart.
At invocation time, the agent runtime injects the tool’s parameter schema into the execution environment. The most common patterns are:
TOOL_INPUT set to a JSON string containing all declared parameters. The tool reads this variable, parses it, and proceeds.sys.stdin (or the language’s equivalent) instead of an env var.Both patterns are supported by most runtimes; which one is used is determined at registration time. A tool that needs to support both might start like this:
import sys, json, os
def read_payload():
source = os.environ.get("TOOL_INPUT")
if source:
return json.loads(source)
# fallback to stdin
raw = sys.stdin.read()
if not raw.strip():
raise ValueError("no input received")
return json.loads(raw)
When the tool produces output, it must write a single JSON object to stdout. The runtime captures that object and merges it into the agent’s message history (typically as a tool message role). If the output contains a key the agent recognizes—such as text, data, or error—the agent can conditionally continue reasoning or surface the result to the user.
If the tool writes more than one JSON object, or writes JSON interspersed with plain‑text logs, the runtime typically discards the extra payload and only processes the first complete object. This is a frequent source of silent failures: developers add print("debug info") for local troubleshooting, not realizing the agent runtime will ignore everything after the first JSON line.
Tools often need access to secrets—database passwords, API keys, TLS certificates. Hard‑coding these into the container image is a security anti‑pattern and makes the tool non‑portable across environments. The standard approach is to inject secrets at runtime via environment variables or mounted secrets stores.
When the manifest declares an env block, the runtime is responsible for populating those variables before launching the container or process. For example, a tool that connects to a PostgreSQL instance might declare:
{
"env": {
"PGHOST": "$DB_HOST",
"PGUSER": "$DB_USER",
"PGPASSWORD": "$DB_PASSWORD",
"PGDATABASE": "$DB_NAME"
}
}
The operator deploying the agent runtime sets $DB_HOST, $DB_USER, etc., from a secret management system (HashiCorp Vault, AWS Secrets Manager, Kubernetes Secret objects, etc.). The tool itself never sees the plaintext values unless the operator has deliberately injected them.
A frequent sharp edge: if the tool’s manifest lists an env var but the operator’s deployment omits it, the tool either fails with a KeyError/NameError (if the script reads it unconditionally) or proceeds with a default/empty value, producing subtly wrong results. There is no universal “missing env var” error from the runtime; the failure mode is entirely determined by the tool’s code.
Another edge case involves variable name collisions. If the agent runtime also sets TOOL_INPUT or PATH, and the tool’s own script uses those names, the runtime’s values win. Tools that embed their own config logic should prefix all internal variables (e.g., MYTOOL_DB_HOST) to avoid overlap.
When a tool fails to execute, the agent runtime usually returns an error object that includes the exit code, the first 512 bytes of stderr, and sometimes a truncated stdout. Reading this response is the first step in troubleshooting.
Common failure patterns and their typical signals:
| Symptom | Likely cause | Check |
|---|---|---|
| Exit code 127 or “command not found” | Executable not in PATH or not marked +x | which python3 inside the container; ls -la /tool.py |
| Exit code 1 with “invalid TOOL_INPUT” | Payload doesn’t match declared schema or JSON parse error | Verify the TOOL_INPUT env var or stdin content; run the script manually with the same payload |
| Exit code 137 (SIGKILL) or 143 | Timeout exceeded or explicit kill | The manifest’s timeout_seconds was honored; increase if the tool legitimately needs more time |
| Exit code 0 but stdout contains no valid JSON | Tool wrote logs or debug prints before the result | Restructure the script to write the result first, or redirect debug output to stderr |
| Tool runs locally fine but fails when invoked via the runtime | Environment mismatch (missing env vars, different PATH, cgroup limits) | Replicate the runtime’s environment locally: docker run --env-file=.env my-tool:latest |
For ongoing monitoring, many operators pipe the agent runtime’s logs to a central system (ELK, Loki, Splunk). A tool’s stderr and stdout are typically tagged with the tool’s registered name and the request ID, making it possible to grep for patterns like csv_to_json and Error across a deployment’s lifetime.
If the runtime supports it, you can also request a liveness probe or health check endpoint before full invocation. A GET /tools/csv_to_json/health might return 200 if the container starts and can read its env vars, or 500 if the executable fails immediately. This is useful in orchestrated environments where tools are registered and unregistered dynamically.
Even when every step above appears correct, several “invisible” failure modes surface only in production or after repeated use:
parameters.type: "object" with a properties block, but the runtime passes an array or a scalar. Some frameworks silently coerce; others reject the invocation and log a schema validation error. The behavior is runtime‑specific and often undocumented until the first mismatch.data field, but the agent only sees the first few hundred bytes.tool message. The agent may interpret this as success, but downstream consumers expecting a result will find nothing.' to \"). If the tool’s script passes those vars to a shell command via os.system() or subprocess.run(["sh", "-c", ...]), the sanitized value may break the intended command. Prefer passing secrets directly to the tool’s own logic rather than routing them through a shell.Understanding these edges comes from watching the runtime’s logs after the first production deployment, not from reading the reference documentation alone. The patterns above are what most frameworks provide; the specifics—how a given runtime interprets a missing timeout_seconds, or whether it retries on non‑zero exit—are details you’ll need to verify against your own deployment.
Not every capability requires a custom tool. If the operation can be expressed as a SQL query, a curl call from the agent’s process, or a shell pipeline, prefer those channels—they are already understood by the runtime, require no container management, and have established debugging ergonomics. Agent tool creation should be reserved for cases where:
curl cannot).When in doubt, start with the simplest channel that meets the requirement, and only graduate to a dedicated tool when the constraints of that channel become a blocker.
This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy