{ "cells": [ { "cell_type": "markdown", "id": "overview", "metadata": {}, "source": [ "# Build a ChatGPT plugin with the OpenAI Agents SDK and Amazon Bedrock AgentCore\n", "\n", "In this cookbook, you'll build a private flight assistant for a fictional airline and learn how to connect ChatGPT to an OpenAI Agents SDK workflow backed by Amazon Bedrock. The sample airline is called **Eliza Airlines**; its `ELZ` flights use sample data and cannot be booked, changed, or canceled.\n", "\n", "By the end, you'll know how to:\n", "\n", "- expose read-only tools to ChatGPT and validate their inputs and outputs;\n", "- connect a private tool server through OpenAI Secure MCP Tunnel;\n", "- run an Agents SDK workflow with a Bedrock model and display its results in a ChatGPT widget;\n", "- check the integration locally, evaluate fresh agent responses, and verify where traces arrive.\n", "\n", "The default path runs the agent on your workstation. You'll start with checks that need no cloud credentials, then choose whether to run the agent with Bedrock and connect it to ChatGPT. An existing Amazon Bedrock AgentCore Runtime is an optional hosting alternative; this notebook does not deploy one.\n", "\n", "A joint cookbook by Eliza and OpenAI.\n" ] }, { "cell_type": "markdown", "id": "architecture", "metadata": {}, "source": [ "## How the pieces fit together\n", "\n", "**Model Context Protocol (MCP)** lets ChatGPT discover tools, call them with structured inputs, and receive structured results. The **MCP adapter** in this repository is the server that exposes our three flight tools. It checks the request, runs the agent, and validates the response before returning it to ChatGPT.\n", "\n", "![Default request flow: ChatGPT sends a tool call through the hosted tunnel and local tunnel-client to the MCP adapter and local Agents SDK agent. The agent calls Amazon Bedrock and exports traces to AWS.](images/cookbook-boundaries.svg)\n", "\n", "The arrows follow a tool request. The result returns along the same path, and the **widget**, a small HTML view inside ChatGPT, displays the validated result. In MCP, that result is carried in the `structuredContent` field. The widget does not call the flight backend itself.\n", "\n", "The `tunnel-client` on your workstation opens an outbound HTTPS connection to OpenAI's hosted tunnel endpoint. That connection lets ChatGPT reach the adapter at `127.0.0.1:8787/mcp`. This address is **loopback**: it is reachable only on the same machine. You do not need a public MCP URL or an inbound firewall rule.\n", "\n", "The **OpenAI Agents SDK** runs the Python workflow and its function tools. **Amazon Bedrock** supplies the model through an OpenAI-compatible endpoint. **AgentCore Observability** receives traces, which record the steps, timing, and errors in a run. A **span** records one operation within a trace, such as a model or tool call.\n", "\n", "Two options build on the default path shown above:\n", "\n", "- An existing **AgentCore Runtime**, AWS's managed agent hosting service, can run the workflow instead of your workstation. Its owner supplies the Runtime's **Amazon Resource Name (ARN)**, an AWS resource identifier, and an invoke-only role. The owner manages deployment, credentials, and operations.\n", "- `COOKBOOK_TRACING_MODE=dual` adds OpenAI Traces alongside AWS observability. It requires a separate OpenAI Platform trace key. The default, `aws`, exports only to AWS.\n", "\n", "Your Platform administrator must provision the hosted tunnel and associate it with your OpenAI organization and ChatGPT workspace. Follow the [README permission matrix](../README.md#enterprise-least-privilege-matrix) before any credentialed step. Your team also owns identity, secret delivery, hosting, and retention. The [architecture guide](../docs/openai-agentkit-cookbook.md#architecture-boundaries) covers those responsibilities in detail.\n" ] }, { "cell_type": "markdown", "id": "prereqs", "metadata": {}, "source": [ "## Prerequisites\n", "\n", "You'll need basic Python and command-line experience, plus:\n", "\n", "- Python 3.10 or newer;\n", "- [`uv`](https://docs.astral.sh/uv/getting-started/installation/), which installs and runs the Python environment;\n", "- JupyterLab from the locked development environment, using the [README launch command](../README.md#optional-notebook-and-developer-checks);\n", "- Node.js 24 or newer and npm for the MCP adapter and evaluation tools.\n", "\n", "The local checks use sample data and need no cloud credentials. Live steps require the access listed in the [README permission matrix](../README.md#enterprise-least-privilege-matrix) and can incur model, telemetry, or Runtime charges.\n", "\n", "The setup cell locates the repository and imports [notebook helpers](../runtime-agent/notebook_helpers.py). Those helpers handle subprocess timeouts, limited output capture, credential filtering, service cleanup, and evaluation reports. The request and response examples stay in the notebook.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "setup", "metadata": {}, "outputs": [], "source": [ "import json\n", "import os\n", "import shutil\n", "import sys\n", "import urllib.request\n", "from pathlib import Path\n", "\n", "REPO_ROOT = next(\n", " (path for path in (Path.cwd(), *Path.cwd().parents)\n", " if (path / \"runtime-agent\" / \"pyproject.toml\").exists()\n", " and (path / \"mcp-adapter\" / \"package.json\").exists()),\n", " None,\n", ")\n", "if REPO_ROOT is None:\n", " raise RuntimeError(\"Run this notebook from the cookbook repository or notebooks directory.\")\n", "RUNTIME_DIR, MCP_DIR = REPO_ROOT / \"runtime-agent\", REPO_ROOT / \"mcp-adapter\"\n", "sys.path.insert(0, str(RUNTIME_DIR))\n", "\n", "from demo_date import demo_travel_date\n", "from notebook_helpers import (\n", " live_runtime_environment, local_runtime_service, run,\n", " run_agent_evaluation, selected_environment,\n", ")\n", "\n", "DEMO_TRAVEL_DATE = demo_travel_date()\n", "UV, NODE, NPM = (shutil.which(command) for command in (\"uv\", \"node\", \"npm\"))\n", "if not UV or not NODE or not NPM:\n", " raise RuntimeError(\"Install uv and Node.js/npm before executing the notebook.\")\n", "print(\"Repository:\", REPO_ROOT)\n", "print(\"Commit:\", run([\"git\", \"rev-parse\", \"HEAD\"], REPO_ROOT).stdout.strip())\n", "for name, command in ((\"uv\", UV), (\"Node\", NODE), (\"npm\", NPM)):\n", " print(name + \":\", run([command, \"--version\"], REPO_ROOT).stdout.strip())\n" ] }, { "cell_type": "markdown", "id": "deps-intro", "metadata": {}, "source": [ "## 1. Install the pinned dependencies\n", "\n", "A **lockfile** records exact dependency versions. The repository includes `uv.lock` and both npm lockfiles so you can reproduce the tested environment. `uv sync --locked` and `npm ci` fail if a manifest disagrees with its lockfile.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "deps", "metadata": {}, "outputs": [], "source": [ "run([UV, \"sync\", \"--locked\", \"--extra\", \"dev\"], RUNTIME_DIR)\n", "run([NPM, \"ci\"], RUNTIME_DIR)\n", "run([NPM, \"ci\"], MCP_DIR)\n", "print(\"Locked dependency environments are ready.\")" ] }, { "cell_type": "markdown", "id": "python-intro", "metadata": {}, "source": [ "## 2. Follow a request through the agent\n", "\n", "A **schema** defines the fields and values a request or response accepts. [RuntimeRequest](../runtime-agent/schemas.py) validates the action and its arguments before any tool runs. For `search_flights`, it requires an origin, destination, and travel date.\n", "\n", "[build_agent](../runtime-agent/agent.py) maps that action to a function tool, a Python function exposed to the model through the Agents SDK. It supplies only the tool for the requested action and tells the model to call it once. The core configuration in `agent.py` is:\n", "\n", "```python\n", "Agent(\n", " name=\"ChatGPT MCP flight cookbook agent\",\n", " instructions=\"Call the selected read-only function tool exactly once and return its JSON.\",\n", " model=model or os.environ.get(MODEL_ENV, DEFAULT_MODEL),\n", " output_type=AgentOutputSchema(dict, strict_json_schema=False),\n", " model_settings=ModelSettings(\n", " parallel_tool_calls=False,\n", " tool_choice=tool_choice,\n", " ),\n", " tools=tools,\n", " tool_use_behavior=\"stop_on_first_tool\",\n", ")\n", "```\n", "\n", "Here, `tools` contains the selected function and `tool_choice` is its name. `stop_on_first_tool` returns the tool's output without asking the model to rewrite it. During a real run, `build_bedrock_model()` supplies the Bedrock client and `Runner.run_sync()` executes this agent. The runner validates the returned JSON as a `RuntimeResponse`.\n", "\n", "First, build a search agent and inspect its tool without calling a model. The sample date defaults to UTC today plus 45 days; `COOKBOOK_DEMO_TRAVEL_DATE` can pin it for repeatable checks.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "inspect-flight-agent", "metadata": {}, "outputs": [], "source": [ "from agent import build_agent\n", "from schemas import RuntimeRequest\n", "\n", "search_request = RuntimeRequest(\n", " action=\"search_flights\",\n", " origin=\"DAL\",\n", " destination=\"MDW\",\n", " travel_date=DEMO_TRAVEL_DATE,\n", ")\n", "flight_agent = build_agent(search_request, execution_mode=\"local\")\n", "print(\"Selected tool:\", flight_agent.tools[0].name)\n", "print(\"After the tool returns:\", flight_agent.tool_use_behavior)\n" ] }, { "cell_type": "markdown", "id": "check-sample-response", "metadata": {}, "source": [ "Now run the Python tests, formatting checks, and type checks, then send the same request through the local entrypoint. `COOKBOOK_FORCE_LOCAL_TOOLS=1` calls the sample functions directly, so this check uses neither a model nor AWS. These functions return the same sample results for the same inputs.\n", "\n", "`executionMode` identifies the selected route: `local` or `deployed`. The older `provider: \"agentcore-runtime\"` field remains for compatibility and does not identify where the agent ran.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "python-checks", "metadata": {}, "outputs": [], "source": [ "run([UV, \"run\", \"pytest\", \"-q\"], RUNTIME_DIR)\n", "run([UV, \"run\", \"ruff\", \"check\", \".\"], RUNTIME_DIR)\n", "run([UV, \"run\", \"ruff\", \"format\", \"--check\", \".\"], RUNTIME_DIR)\n", "run([UV, \"run\", \"pyright\"], RUNTIME_DIR)\n", "\n", "local_env = selected_environment(overrides={\n", " \"COOKBOOK_FORCE_LOCAL_TOOLS\": \"1\",\n", " \"COOKBOOK_EVENT\": search_request.model_dump_json(exclude_none=True),\n", "})\n", "smoke = run([UV, \"run\", \"python\", \"agent.py\"], RUNTIME_DIR, local_env)\n", "local_result = json.loads(smoke.stdout)\n", "assert local_result[\"provider\"] == \"agentcore-runtime\"\n", "assert local_result[\"executionMode\"] == \"local\"\n", "assert local_result[\"action\"] == \"search_flights\"\n", "assert local_result[\"data\"][\"flights\"]\n", "assert all(flight[\"travelDate\"] == DEMO_TRAVEL_DATE for flight in local_result[\"data\"][\"flights\"])\n", "print(json.dumps(local_result, indent=2))\n" ] }, { "cell_type": "markdown", "id": "service-intro", "metadata": {}, "source": [ "## 3. Call the Runtime HTTP interface locally\n", "\n", "The AgentCore Python SDK supplies two HTTP endpoints: `/ping` reports health, and `/invocations` accepts an agent request. The helper starts this server on port 8080 and stops it when the cell finishes, including on failure. The request below takes a flight from the search result and checks its status using the same date.\n", "\n", "This tests the deployed Runtime's interface on your workstation using sample tools. Its entrypoint labels responses `executionMode: \"deployed\"`; that label alone is not evidence of an AWS deployment.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "service-check", "metadata": {}, "outputs": [], "source": [ "first_flight = local_result[\"data\"][\"flights\"][0]\n", "with local_runtime_service(UV, RUNTIME_DIR) as health:\n", " request = urllib.request.Request(\n", " \"http://127.0.0.1:8080/invocations\",\n", " data=json.dumps({\n", " \"action\": \"get_live_status\",\n", " \"flight_number\": first_flight[\"flightNumber\"],\n", " \"origin\": first_flight[\"origin\"],\n", " \"destination\": first_flight[\"destination\"],\n", " \"travel_date\": first_flight[\"travelDate\"],\n", " }).encode(),\n", " headers={\"content-type\": \"application/json\"},\n", " method=\"POST\",\n", " )\n", " with urllib.request.urlopen(request, timeout=10) as response:\n", " invocation = json.loads(response.read())\n", " assert health[\"status\"] == \"Healthy\"\n", " assert invocation[\"executionMode\"] == \"deployed\"\n", " assert invocation[\"action\"] == \"get_live_status\"\n", " assert invocation[\"data\"][\"flight\"][\"flightNumber\"] == \"ELZ1234\"\n", " assert invocation[\"data\"][\"flight\"][\"travelDate\"] == DEMO_TRAVEL_DATE\n", " print(\"Health:\", health)\n", " print(\"Invocation:\", json.dumps(invocation, indent=2))\n" ] }, { "cell_type": "markdown", "id": "mcp-intro", "metadata": {}, "source": [ "## 4. Check the MCP adapter and widget\n", "\n", "The adapter exposes `search_flights`, `get_upcoming_status`, and `get_live_status` over **Streamable HTTP**, the MCP transport used to exchange messages over HTTP. Each tool accepts a defined input schema and returns an action-specific output schema. The tools are **idempotent**: repeating a call does not change the sample data.\n", "\n", "The TypeScript tests exercise tool discovery, calls, response validation, and the AWS invocation code with a fake AWS sender. They also check the widget's versioned resource URI, content type (MIME type), and **Content Security Policy (CSP)**, which restricts the resources it can load. The widget uses `textContent` to display result text without treating it as HTML. These tests make no live AWS calls.\n", "\n", "The key boundary is in [server.ts](../mcp-adapter/server.ts): the adapter returns validated data as `structuredContent`, and [flight-widget.html](../mcp-adapter/public/flight-widget.html) renders it when it receives `ui/notifications/tool-result`.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "mcp-checks", "metadata": {}, "outputs": [], "source": [ "run([NPM, \"run\", \"typecheck\"], MCP_DIR)\n", "run([NPM, \"test\"], MCP_DIR)\n", "run([NPM, \"run\", \"build\"], MCP_DIR)\n", "\n", "widget = (MCP_DIR / \"public\" / \"flight-widget.html\").read_text(encoding=\"utf-8\")\n", "assert \"ui/notifications/tool-result\" in widget\n", "assert \"textContent\" in widget\n", "assert \"