AI Agent Development Cheat Sheet: LangGraph, OpenAI Agents SDK, MCP and Evaluation Basics

A working reference for the four things you touch on every agent project: the orchestration graph, the agent runtime, the tool protocol, and the evaluation loop. Code is current as of September 2026. Links go to primary docs, because these APIs move.

Pick your layer first

Layer What it gives you Reach for it when
LangGraph Explicit state machine: nodes, edges, conditional routing, checkpointed state You need loops, branching, human-in-the-loop pauses, or several cooperating agents
OpenAI Agents SDK A runner that executes the tool loop, handoffs, guardrails, sessions, tracing You want the loop run for you and one specialist or a small team of agents
MCP A standard protocol for exposing tools, resources and prompts to any host Your tools should be reusable across hosts instead of hard-wired into one app
Evals Datasets, graders, trajectory checks, regression runs Always. Without this you cannot tell whether a change helped

These are not competitors. A common production shape is a LangGraph graph whose nodes call agents, with tools exposed over MCP, and an eval suite running against recorded traces.

LangGraph

Docs: LangGraph Graph API. Requires Python 3.10 or later. Install with pip install langgraph.

Minimal graph

from typing_extensions import TypedDict

from typing import NotRequired

from langgraph.graph import StateGraph, START, END

 

class State(TypedDict):

    topic: str

    result: NotRequired[str]

 

def work(state: State):

    return {“result”: f”handled {state[‘topic’]}”}   # return a partial update

 

builder = StateGraph(State)

builder.add_node(“work”, work)

builder.add_edge(START, “work”)

builder.add_edge(“work”, END)

graph = builder.compile()

 

graph.invoke({“topic”: “refunds”})

Conditional routing and a tool loop

from langgraph.prebuilt import ToolNode, tools_condition

 

builder = StateGraph(State)

builder.add_node(“agent”, call_model)

builder.add_node(“tools”, ToolNode(tools))

builder.add_edge(START, “agent”)

builder.add_conditional_edges(“agent”, tools_condition)  # -> “tools” or END

builder.add_edge(“tools”, “agent”)

graph = builder.compile()

Message state

from typing import Annotated, Sequence

from langchain_core.messages import BaseMessage

from langgraph.graph.message import add_messages

 

class AgentState(TypedDict):

    messages: Annotated[Sequence[BaseMessage], add_messages]  # appends, not replaces

Persistence and threads

from langgraph.checkpoint.memory import InMemorySaver

 

graph = builder.compile(checkpointer=InMemorySaver())

config = {“configurable”: {“thread_id”: “user-42”}}

graph.invoke({“topic”: “refunds”}, config)   # same thread_id resumes state

  • InMemorySaver is for development only. It loses everything on restart.
  • Local persistence: SqliteSaver. Managed Postgres: AsyncPostgresSaver.
  • Prebuilt shortcut: create_react_agent in langgraph.prebuilt, also exposed as create_agent in langchain.agents in v1. Start prebuilt, drop to StateGraph when you need extra state keys or custom branching.
  • Runaway loops raise GraphRecursionError. Lower recursion_limit while debugging and add an explicit exit condition in state.

OpenAI Agents SDK

Docs: OpenAI Agents SDK. Install with pip install openai-agents. Provider-agnostic, and uses the Responses API by default for OpenAI models.

Hello world

from agents import Agent, Runner

 

agent = Agent(name=”Assistant”, instructions=”You are a helpful assistant”)

result = Runner.run_sync(agent, “Write a haiku about recursion.”)

print(result.final_output)

Function tools

from agents import Agent, Runner, function_tool

 

@function_tool

def get_weather(city: str) -> str:

    “””Return the weather for a city.”””      # docstring becomes the description

    return f”Sunny in {city}”

 

agent = Agent(name=”Weather”, instructions=”Be brief.”, tools=[get_weather])

result = await Runner.run(agent, input=”Weather in Lviv?”)

Handoffs

spanish = Agent(name=”Spanish agent”, instructions=”You only speak Spanish.”)

english = Agent(name=”English agent”, instructions=”You only speak English.”)

 

triage = Agent(

    name=”Triage agent”,

    instructions=”Handoff to the agent matching the language of the request.”,

    handoffs=[spanish, english],

)

result = await Runner.run(triage, input=”Hola, como estas?”)

Guardrails

# A guardrail returns GuardrailFunctionOutput; set tripwire_triggered to stop the run.

# The runner then raises InputGuardrailTripwireTriggered or

# OutputGuardrailTripwireTriggered, which you catch and handle.

 

agent = Agent(

    name=”Support”,

    instructions=”Help the customer.”,

    input_guardrails=[no_pii],

    output_guardrails=[no_promises],

)

  • Input guardrails run in parallel with the agent and only on the first agent in a run.
  • Handoffs bypass the function-tool pipeline, so tool guardrails do not apply to the handoff call itself.
  • Hosted tools such as WebSearchTool, FileSearchTool, HostedMCPTool, CodeInterpreterTool and ImageGenerationTool also skip the tool-guardrail pipeline.
  • Sessions give you conversation history across runs. Tracing is built in. Lifecycle callbacks come from RunHooks and AgentHooks, including on_agent_start, on_llm_end, on_agent_end and on_handoff.
  • Force a tool call with ModelSettings.tool_choice. Expose an agent as a tool with Agent.as_tool(). Copy with agent.clone(), and pass a new list if you do not want the clone sharing the original tools list.
  • Pass dependencies through context=… on Runner.run(), and every agent, tool and handoff receives it.

MCP

Three primitives, one message format. Tools are callable actions, resources are data addressed by URI, prompts are reusable templates. Everything travels as JSON-RPC 2.0 over stdio or Streamable HTTP, and SSE is deprecated though still supported by some tooling. Spec changes below come from the MCP specification revision of 28 July 2026.

Client call, Python SDK

import asyncio

from mcp import Client

 

async def main() -> None:

    async with Client(“http://localhost:8000/mcp”) as client:

        result = await client.call_tool(“add”, {“a”: 1, “b”: 2})

        print(result.structured_content)      # {‘result’: 3}

 

asyncio.run(main())

 

# A URL means Streamable HTTP. Client can also launch a local server

# as a stdio subprocess, or take a custom transport.

What changed in the 2026-07-28 revision

Change What it means for you
Mcp-Method and Mcp-Name headers required on Streamable HTTP Gateways, rate limiters and WAFs can route and meter without parsing JSON bodies
ttlMs and cacheScope on tools/list, prompts/list, resources/list, resources/read Capability listings are cacheable, so stop re-listing on every turn
MRTR replaces server-initiated elicitation, sampling and roots requests Server returns resultType “input_required” with what it needs, and the client retries with inputResponses attached
Tasks moved to the io.modelcontextprotocol/tasks extension Long-running work is polled through tasks/get rather than held open
  • Transport rule of thumb: stdio for local and most interoperable, Streamable HTTP for anything remote.
  • HTTP servers use a subset of OAuth 2.1. An unauthenticated request should get a 401 with a WWW-Authenticate header pointing at protected resource metadata.
  • Treat every tool result as untrusted input. Text inside a document or page can contain instructions, and that is prompt injection with a delivery mechanism.

Evaluation basics

An agent without evals is a demo. The minimum viable setup is a dataset of real inputs with known-good outcomes, a grader per outcome type, and a run you can repeat on every change.

What to measure How Catches
Final answer quality Exact match, or an LLM judge with a rubric and few-shot examples Regressions from prompt, model or retrieval changes
Tool choice Assert which tools were called, in what order The agent taking an expensive or wrong path to a right answer
Trajectory Step count, loops, retries per run Runaway loops and quiet cost growth
Retrieval Precision and recall of retrieved passages against labelled sets Answers that are right for the wrong reason
Refusal behaviour Cases where the correct output is I do not know Confident answers with no grounding
Cost and latency Tokens and wall clock per completed task, p50 and p95 The version that got better and twice as expensive
  • Build the dataset from production traces, not imagination. Twenty real cases beat two hundred invented ones.
  • Version the eval set. When it changes, say so, or your trend line is meaningless.
  • Grade the steps, not only the ending. Two runs with the same answer and different tool paths are not equally good.
  • Pin your model version in CI. A silent provider update is otherwise indistinguishable from your own regression.
  • Keep a small adversarial set: prompt injection in tool output, missing data, contradictory instructions, and inputs where refusing is correct.

Failure modes worth memorising

  • No exit condition. Add a step budget in state and a recursion limit, not just a hopeful prompt.
  • Tool descriptions written for humans. The model reads them as the spec, so name arguments precisely and say what the tool must not be used for.
  • Silent retries. Retrying a non-idempotent tool call duplicates the side effect. Make writes idempotent or record an operation key.
  • Unbounded context. Every appended message is paid for on every subsequent turn. Summarise or window it deliberately.
  • State stored only in the transport. If a restart loses the run, it was never persisted. Compile with a checkpointer.
  • Permissions ignored during retrieval. Access rules do not survive into an index unless someone carries them across and filters per user.
  • No human gate on consequential actions. Anything that spends money, emails a customer or writes to a system of record needs an approval step and a log.

Credits

Compiled by the AI agent development team at https://litslink.com/. Verify APIs against the primary documentation linked above before shipping, since all three move quickly.

Leave a Reply

Your email address will not be published. Required fields are marked *