MCP+

MCP & AI Agent Master Cheat Sheet

MODEL CONTEXT PROTOCOL ยท AGENTIC AI ยท JAVASCRIPT / TYPESCRIPT ยท COMPLETE END-TO-END REFERENCE

๐ŸŽ“ Next Gen QA IT Coaching Classes
๐Ÿ“ž Mr. Khan Sir  |  8700350994
MCP TS SDK OpenAI Agents SDK LangGraph.js AutoGen Vercel AI SDK Multi-Agent
1. MCP Protocol & Lifecycle · 2. Advanced Tools · 3. Resource Templates/Subscriptions · 4. Advanced Prompts & Completion
1. Protocol Layers & Lifecycle
JSON-RPC 2.0 message shape
{ "jsonrpc":"2.0", "id":1, "method":"tools/call", "params":{ "name":"get_ticket", "arguments":{id:"QA-1"} } } // notifications = no "id" field, no response expected
Handshake sequence
client → "initialize" {protocolVersion, capabilities} server → returns its capabilities (tools/resources/prompts) client → "notifications/initialized" // only now can normal requests flow
2. Advanced Tool Definition
Structured output + annotations + try/catch
server.registerTool("create_jira_issue", { inputSchema:{project:z.string(),summary:z.string()}, outputSchema:{issueKey:z.string(),url:z.string()}, annotations:{readOnlyHint:false,destructiveHint:true} }, async ({project,summary}) => { try { const i = await jiraApi.create({project,summary}); return {structuredContent:{issueKey:i.key,url:i.url}, content:[{type:"text",text:`Created ${i.key}`}]}; } catch(e){ return {isError:true,content:[{type:"text",text:e.message}]}; } });
3. Resource Templates & Subscriptions
Dynamic URI template (RFC 6570)
import{ResourceTemplate}from "@modelcontextprotocol/sdk/server/mcp.js"; server.registerResource("ticket", new ResourceTemplate("jira://ticket/{id}",{list:undefined}), {title:"Jira Ticket"}, async(uri,{id})=>({contents:[{uri:uri.href, mimeType:"application/json", text:JSON.stringify(await getTicket(id))}]}) );
Push update notifications
server.sendResourceListChanged(); server.sendResourceUpdated({uri:"jira://ticket/QA-1"});
4. Advanced Prompts & Argument Completion
Multi-arg prompt w/ embedded resource
server.registerPrompt("triage-bug",{ argsSchema:{logUrl:z.string(),severity:z.enum(["P1","P2"])} },async({logUrl,severity})=>({messages:[ {role:"user",content:{type:"text",text:`Triage ${severity} bug`}}, {role:"user",content:{type:"resource",resource:{uri:logUrl}}} ]}));
Argument autocompletion
server.registerCompletion(async (ref,arg)=> ({values:["P1","P2","P3"].filter(v=>v.startsWith(arg.value))}));
5. Sampling (Server→LLM) · 6. Roots & Boundaries · 7. Progress/Cancellation/Logging · 8. Pagination & Multi-Content Results
5. Sampling โ€“ Server Asks Client's LLM
Server requests a completion via the client's model
const res = await server.server.createMessage({ messages:[{role:"user",content:{type:"text", text:"Summarize this log in 1 line"}}], maxTokens: 100 }); // lets a tool call back into the LLM w/o owning API keys
6. Roots โ€“ Filesystem Boundaries
Client tells server which folders are in-scope
client.setRequestHandler("roots/list", async () => ({ roots: [{ uri: "file:///Users/amirkhan/IdeaProjects", name: "Projects" }] })); // server must only read/write within declared roots
7. Progress, Cancellation & Logging
Report progress on a long tool call
async ({file}, {sendNotification, _meta}) => { for(let i=0;i<100;i+=20){ await sendNotification({method:"notifications/progress", params:{progressToken:_meta.progressToken, progress:i, total:100}}); } }
Server-side log levels to client
server.sendLoggingMessage({level:"info", data:"Tool started"});
8. Pagination & Multi-Content Results
Cursor-based pagination for list ops
{ "method":"resources/list", "params":{cursor:"eyJvZmZzZXQiOjEwfQ"} } // response includes nextCursor if more items exist
Return image/audio/embedded-resource content
return { content: [ { type: "text", text: "Screenshot captured" }, { type: "image", data: base64Png, mimeType: "image/png" } ]};
9. Streamable HTTP Transport · 10. MCP Client Advanced · 11. Host Configs (Multi-Server) · 12. Debugging, Inspector & Unit Tests
9. Streamable HTTP (Remote Server)
Express + session-scoped transport
import express from "express"; import{StreamableHTTPServerTransport}from "@modelcontextprotocol/sdk/server/streamableHttp.js"; const app=express(); app.use(express.json()); const transports:Record<string,StreamableHTTPServerTransport>={}; app.post("/mcp", async(req,res)=>{ const sid=req.headers["mcp-session-id"] as string; let t=transports[sid]; if(!t){ t=new StreamableHTTPServerTransport({ sessionIdGenerator:()=>crypto.randomUUID()}); await server.connect(t); } await t.handleRequest(req,res,req.body); });
10. MCP Client Advanced
Connect multiple servers, aggregate tools
const clients=new Map<string,Client>(); for(const[name,cfg] of Object.entries(mcpServers)){ const c=new Client({name,version:"1.0"}); await c.connect(new StdioClientTransport(cfg)); clients.set(name,c); } const allTools=(await Promise.all( [...clients.values()].map(c=>c.listTools()))).flat();
Elicitation โ€“ server asks user for input
client.setRequestHandler("elicitation/create", async(req)=>({action:"accept",content:{confirm:true}}));
11. Host Configs (Multi-Server)
claude_desktop_config.json
{ "mcpServers":{ "jira":{"command":"node","args":["./build/jira.js"], "env":{"JIRA_TOKEN":"${JIRA_TOKEN}"}}, "playwright":{"command":"npx","args":["@playwright/mcp@latest"]}, "remote-api":{"url":"https://mcp.example.com/mcp"} }}
12. Debugging, Inspector & Unit Tests
Launch Inspector against a built server
npx @modelcontextprotocol/inspector node build/index.js // UI at localhost:6274 to list/call tools live
Unit test a tool handler directly
import{describe,it,expect}from "vitest"; describe("create_jira_issue",()=>{ it("returns issue key",async()=>{ const res=await handler({project:"QA",summary:"Bug"}); expect(res.structuredContent.issueKey).toMatch(/QA-\d+/); }); });
13. Agent Loop Internals · 14. Agents SDK Runner & Streaming · 15. Tools & MCP Integration · 16. Handoffs & Guardrails
13. Agent Loop Internals
The actual loop under the hood
while(!done){ response=await llm.call(messages,tools); if(response.toolCalls.length){ for(const call of response.toolCalls){ result=await executeTool(call); messages.push({role:"tool",content:result}); } } else { done=true; } }
Context window management
// trim/summarize old turns before token limit // keep: system prompt + last N turns + tool results
14. OpenAI Agents SDK โ€“ Runner & Streaming
Structured output via zod
import{Agent,run,Runner}from "@openai/agents"; const TestPlan=z.object({steps:z.array(z.string())}); const agent=new Agent({name:"QA Planner",model:"gpt-4.1",outputType:TestPlan}); const runner=new Runner({maxTurns:10}); const result=await runner.run(agent,"Plan login tests"); console.log(result.finalOutput.steps);
Streaming token-by-token
const stream=await run(agent,input,{stream:true}); for await(const ev of stream){ if(ev.type==="raw_model_stream_event") process.stdout.write(ev.delta); }
15. Tools & MCP Integration
Function tool w/ zod, strict typing
import{tool}from "@openai/agents"; const getTicket=tool({name:"get_jira_ticket", description:"Fetch ticket by ID", parameters:z.object({id:z.string()}), strict:true, execute:async({id})=>await fetchTicket(id) });
Plug an MCP server in as tool source
import{MCPServerStdio}from "@openai/agents"; const mcp=new MCPServerStdio({command:"node",args:["./jira-mcp/build/index.js"]}); await mcp.connect(); const agent=new Agent({name:"QA",mcpServers:[mcp]});
16. Handoffs & Guardrails
Handoff w/ input filter + tool name override
import{handoff}from "@openai/agents"; const toBilling=handoff(billingAgent,{ toolNameOverride:"escalate_to_billing", inputFilter:(h)=>h.filter(m=>m.role!=="system")}); const triage=new Agent({name:"Triage",handoffs:[toBilling]});
Input/output guardrails w/ tripwire
const piiGuard={name:"no-pii", execute:async({input})=>({tripwireTriggered:/\d{10}/.test(input)})}; const agent=new Agent({...,inputGuardrails:[piiGuard]});
17. Tracing & Sessions · 18. Lifecycle Hooks & Model Settings · 19. Human Approval & RunContext · 20. Agent-as-Tool
17. Tracing & Sessions
Group multiple runs under one trace
import{withTrace}from "@openai/agents"; await withTrace("qa-workflow",async()=>{ await run(plannerAgent,input); await run(executorAgent,input); });
Persistent session memory
import{SQLiteSession}from "@openai/agents"; const session=new SQLiteSession("user-123"); await run(agent,"continue where we left off",{session});
18. Lifecycle Hooks & Model Settings
Hooks for observability
const agent=new Agent({ name:"QA", hooks:{ onStart:()=>console.log("start"), onToolStart:(c,t)=>console.log("tool:",t.name), onEnd:(c,out)=>console.log("done",out) } });
Model settings (temp, tool_choice, parallel)
const agent=new Agent({..., modelSettings:{ temperature:0.2, toolChoice:"auto", parallelToolCalls:true }});
19. Human Approval & RunContext
Require approval before a risky tool runs
const deleteTool=tool({name:"delete_env", needsApproval:true, execute:async()=>wipeEnv()}); if(result.interruptions?.length){ const approved = await askUser("Approve delete?"); await runner.resume(result, {approve: approved}); }
RunContext โ€“ dependency injection
const agent=new Agent<{ userId:string }>({...}); await run(agent, input, { context: { userId: "amir" } });
20. Agent-as-Tool Pattern
Use one agent as a callable tool for another
const summarizer = new Agent({ name:"Summarizer" }); const summarizerTool = summarizer.asTool({ toolName:"summarize_text", toolDescription:"Summarizes text" }); const mainAgent = new Agent({ tools:[summarizerTool] }); // avoids a full handoff; keeps mainAgent in control
21. LangGraph.js Graph & State · 22. Conditional Edges & ToolNode · 23. Persistence & Human-in-Loop · 24. Subgraphs, Send API & Streaming
21. LangGraph.js โ€“ Graph & Typed State
Annotated state with reducer
import{StateGraph,Annotation,END,START}from "@langchain/langgraph"; const AgentState=Annotation.Root({ messages: Annotation<BaseMessage[]>({ reducer:(x,y)=>x.concat(y), default:()=>[] }) }); const graph=new StateGraph(AgentState) .addNode("agent",callModelNode) .addNode("tools",toolNode) .addEdge(START,"agent");
22. Conditional Edges & Prebuilt ToolNode
Route on whether the model called a tool
import{ToolNode,createReactAgent}from "@langchain/langgraph/prebuilt"; graph.addNode("tools",new ToolNode([getTicketTool,createIssueTool])); graph.addConditionalEdges("agent",(state)=>{ const last=state.messages.at(-1); return last.tool_calls?.length ? "tools" : END; }); graph.addEdge("tools","agent");
Prebuilt ReAct agent (one-liner)
const app = createReactAgent({ llm: model, tools: [getTicketTool] });
23. Persistence & Human-in-the-Loop
Checkpointer + interrupt for approval
import{MemorySaver}from "@langchain/langgraph"; const app=graph.compile({ checkpointer:new MemorySaver(), interruptBefore:["tools"] }); const config={configurable:{thread_id:"run-1"}}; await app.invoke({messages:[...]},config); // resume after human approval: await app.invoke(null,config);
24. Subgraphs, Send API & Streaming Modes
Send API โ€“ dynamic parallel fan-out (map-reduce)
import{Send}from "@langchain/langgraph"; function fanOut(state){ return state.tickets.map(t => new Send("analyzeOne", { ticket: t })); } graph.addConditionalEdges("split", fanOut);
Streaming modes
for await (const chunk of await app.stream(input, { streamMode: "values" })) { /* "values"|"updates"|"messages" */ }
25. AutoGen Core & JS Equivalent · 26. AutoGen SelectorGroupChat & State Save/Load · 27. Multi-Agent Patterns · 28. Advanced Multi-Agent Patterns
25. AutoGen Core (Python) + JS Equivalent
AutoGen has no official JS SDK. In TS, replicate the pattern manually or via LangGraph.js.
AutoGen โ€“ RoundRobinGroupChat
from autogen_agentchat.teams import RoundRobinGroupChat team = RoundRobinGroupChat([writer, reviewer], max_turns=6)
JS/TS manual round-robin equivalent
const agents=[writerAgent,reviewerAgent]; let msgs=[input]; for(let i=0;i<6;i++){ const cur=agents[i%agents.length]; const res=await run(cur,msgs.join("\n")); msgs.push(res.finalOutput); }
26. SelectorGroupChat & State Save/Load
AutoGen โ€“ model picks next speaker
from autogen_agentchat.teams import SelectorGroupChat team = SelectorGroupChat(agents, model_client=model, selector_prompt="Pick the best next agent")
AutoGen โ€“ save/load team state
state = await team.save_state() # ...later, resume from saved checkpoint await team.load_state(state)
JS/TS equivalent selector via LLM router
const pick = await run(routerAgent, `Who should reply next? ${msgs}`); const next = agents.find(a => a.name === pick.finalOutput);
27. Multi-Agent Patterns
Supervisor (planner delegates to specialists)
const supervisor=new Agent({name:"Supervisor", handoffs:[researchAgent,codeAgent,testAgent], instructions:"Route task to the right specialist"});
Sequential pipeline (A output → B input)
const plan=await run(plannerAgent,goal); const code=await run(coderAgent,plan.finalOutput); const tested=await run(testerAgent,code.finalOutput);
28. Advanced Patterns: Swarm, Debate, Voting
Blackboard / Swarm โ€“ shared state, event-driven
// all agents read/write one shared "blackboard" state // each contributes only when its condition matches // good for non-linear, exploratory reasoning
Debate + Voting / Consensus
const opinions = await Promise.all( panel.map(a => run(a, question))); const final = await run(judgeAgent, `Pick best answer: ${opinions.map(o=>o.finalOutput)}`);
29. Vercel AI SDK โ€“ Tools & Structured Output · 30. Vercel AI SDK + MCP · 31. Security & Production Practices · 32. Testing, Deployment & Common Errors
29. Vercel AI SDK โ€“ Tools & generateObject
Tool calling with generateText
import{generateText,tool}from "ai"; import{openai}from "@ai-sdk/openai"; const{text}=await generateText({ model: openai("gpt-4.1"), tools: { getTicket: tool({ description: "Get Jira ticket", parameters: z.object({ id: z.string() }), execute: async ({ id }) => fetchTicket(id) }) }, prompt: "Get status of QA-1" });
Structured JSON output
const{object}=await generateObject({ model: openai("gpt-4.1"), schema: TestPlanSchema, prompt: goal });
30. Vercel AI SDK + MCP
Consume an MCP server's tools directly
import{experimental_createMCPClient as createMCPClient}from "ai"; const mcpClient = await createMCPClient({ transport: { type: "stdio", command: "node", args: ["./jira-mcp/build/index.js"] } }); const tools = await mcpClient.tools(); const{text}=await generateText({ model: openai("gpt-4.1"), tools, prompt: goal }); await mcpClient.close();
31. Security & Production Practices
OAuth 2.1 on a remote MCP server
app.use("/mcp",async(req,res,next)=>{ const token=req.headers.authorization?.split(" ")[1]; if(!await verifyToken(token)) return res.status(401).json({error:"unauthorized"}); next(); });
Reliability & cost checklist
โœ” maxTurns cap, retry w/ backoff, timeout each tool โœ” least-privilege scopes per tool, cache tool lists โœ” never log secrets/tokens in traces
32. Testing, Deployment & Common Errors
LayerHow to test
Tool handlerUnit test (vitest/jest)
MCP serverInspector + integration test
Agent runAssert finalOutput schema
ErrorFix
Server exits on startNo console.log in stdio mode
Session lost (HTTP)Persist by mcp-session-id header
Handoff loops foreverCap maxTurns / exit condition