惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Security Archives - TechRepublic
Security Archives - TechRepublic
H
Heimdal Security Blog
T
Tenable Blog
Webroot Blog
Webroot Blog
Cisco Talos Blog
Cisco Talos Blog
NISL@THU
NISL@THU
Help Net Security
Help Net Security
W
WeLiveSecurity
量子位
Stack Overflow Blog
Stack Overflow Blog
Schneier on Security
Schneier on Security
Simon Willison's Weblog
Simon Willison's Weblog
Recorded Future
Recorded Future
Martin Fowler
Martin Fowler
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
L
Lohrmann on Cybersecurity
SecWiki News
SecWiki News
Blog — PlanetScale
Blog — PlanetScale
F
Full Disclosure
Recent Commits to openclaw:main
Recent Commits to openclaw:main
小众软件
小众软件
Cyberwarzone
Cyberwarzone
S
Security Affairs
L
LangChain Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
V
V2EX
WordPress大学
WordPress大学
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
L
LINUX DO - 热门话题
Forbes - Security
Forbes - Security
Engineering at Meta
Engineering at Meta
博客园 - 三生石上(FineUI控件)
Scott Helme
Scott Helme
H
Help Net Security
www.infosecurity-magazine.com
www.infosecurity-magazine.com
C
Cyber Attacks, Cyber Crime and Cyber Security
有赞技术团队
有赞技术团队
IT之家
IT之家
G
Google Developers Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
S
Schneier on Security
Google DeepMind News
Google DeepMind News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
月光博客
月光博客
Hacker News: Ask HN
Hacker News: Ask HN
O
OpenAI News
宝玉的分享
宝玉的分享

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to Build an AI Agent with MCP: A Complete Step-by-Step Guide
Prateek Pareek · 2026-06-26 · via DEV Community

Building AI agents used to mean writing custom glue code for every tool and API you wanted your model to touch. The Model Context Protocol (MCP) changes that entirely. It gives your AI agent one standardized way to connect with any external service, database, or tool, without reinventing the wheel every time. In this guide, you will learn exactly how to build an AI agent with MCP from scratch, step by step, including setup, tool registration, LLM connection, and real code examples.

What is the Model Context Protocol (MCP)?
The Model Context Protocol (MCP) is an open standard that defines how AI models communicate with external tools and services. Instead of writing a new integration for every data source, MCP gives you one protocol that works across all of them.

In simple terms, MCP is the "USB port" for AI agents. Just like USB lets any device talk to any computer, MCP lets any AI model talk to any tool that supports the protocol. Anthropic introduced it in late 2024, and it has since crossed 97 million monthly SDK downloads, with over 13,000 public MCP servers now available.

How MCP differs from traditional AI integration
Traditional AI integrations meant writing a separate connector for every service your model needed to access. You had custom code for your database, a different setup for your file system, and yet another one for your APIs. It was fragile, hard to maintain, and impossible to scale. MCP replaces all of that with a single standardized protocol. You build one MCP server per tool, and any MCP-compatible AI model can use it immediately. No more one-off connectors.

Key components: MCP client, MCP server, and transport layer
There are three core pieces you need to understand. The MCP client is the AI model or agent that sends requests. The MCP server is the tool or service that receives those requests and executes actions. The transport layer is how they talk to each other. For local development, that is stdio (standard input/output). For production and multi-user deployments, you use Streamable HTTP, which replaced the older SSE transport in the June 2025 spec revision.

Why Use MCP to Build AI Agents?
If you are building AI agents that need to interact with real-world tools, MCP is the most practical approach available today. It cuts integration time, improves reliability, and makes your architecture future-proof.

MCP vs RAG: choosing the right approach
RAG (Retrieval-Augmented Generation) is great when your agent needs to look something up from a knowledge base before answering. MCP is better when your agent needs to actually do something: write to a database, call an API, trigger a workflow, or read live data. The clearest way to think about it is this: RAG retrieves, MCP acts. Many production systems use both together. RAG handles passive knowledge lookup while MCP handles active tool execution.

Real-world use cases: database agents, coding assistants, enterprise workflows
The most common use cases right now include database agents (querying and writing to SQL databases through natural language), coding assistants (reading files, running tests, opening pull requests), and enterprise workflow automation (triggering actions across internal tools from a single AI interface). If your agent needs to go beyond answering questions and start taking actions, MCP is the right foundation.

Step-by-Step: Building Your First AI Agent with MCP in Python
This is where we get our hands dirty. The following steps walk you through building a working MCP-powered AI agent in Python using FastMCP, which is the fastest way to spin up an MCP server today.

Step 1: Install dependencies and set up your MCP server
Start by installing the required packages. You need the MCP SDK and FastMCP to build the server, plus the Anthropic SDK if you are using Claude as your LLM.

pip install mcp fastmcp anthropic

Once installed, create a new file called server.py. Import FastMCP and initialize your server with a name.

from fastmcp import FastMCP mcp = FastMCP("my-first-agent")

Step 2: Define and register MCP tools
Tools are the actions your agent can take. You define them as Python functions and decorate them with @mcp.tool() so the server registers them automatically. Keep tool descriptions clear and specific. The LLM reads those descriptions to decide which tool to call.

@mcp.tool() def get_weather(city: str) -> str: """Returns current weather for a given city.""" return f"Weather in {city}: 28 degrees, partly cloudy."

Step 3: Connect an LLM (Claude / GPT-4o) as the agent brain
Now connect your LLM. Your agent needs to know which tools are available so it can decide when to use them. Both Claude and GPT-4o support MCP-style tool calling natively. Pass your registered tools into the LLM API call and let the model handle the reasoning about which tool to trigger and when.

import anthropic client = anthropic.Anthropic() tools = mcp.get_tools() # Fetch registered tools from your MCP server response = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=1024, tools=tools, messages=[{"role": "user", "content": "What is the weather in Mumbai?"}] )

Step 4: Run the agentic loop and handle tool calls
An agentic loop keeps running until the model completes its task. On each iteration, check if the model returned a tool_use block. If it did, execute that tool, pass the result back to the model, and continue. This loop is what transforms a one-shot LLM call into a true AI agent.

while response.stop_reason == "tool_use": tool_block = next(b for b in response.content if b.type == "tool_use") tool_result = mcp.call_tool(tool_block.name, tool_block.input) messages.append({"role": "assistant", "content": response.content}) messages.append({"role": "user", "content": [{"type": "tool_result", "tool_use_id": tool_block.id, "content": tool_result}]}) response = client.messages.create(model="claude-sonnet-4-20250514", max_tokens=1024, tools=tools, messages=messages)

Step 5: Test with MCP Inspector and debug locally
Before you go to production, test your MCP server with the official MCP Inspector. It is a browser-based tool that lets you see exactly which tools your server exposes, call them manually, and inspect the JSON-RPC messages going back and forth. Run npx @modelcontextprotocol/inspector and point it at your server. Fix any tool description issues or schema errors here before connecting a live LLM.

Choosing an Agent Framework: LlamaIndex vs LangChain vs FastMCP
The framework you choose shapes how much code you write and how flexible your agent is. FastMCP is the fastest path for pure MCP server development. It handles server boilerplate so you can focus on defining tools. LlamaIndex integrates naturally with MCP and shines for agents that need to combine tool calling with document retrieval. LangChain offers the widest ecosystem of pre-built components and is a strong choice if you need multi-agent orchestration or complex memory management. For most developers building their first MCP agent, FastMCP plus the Anthropic or OpenAI SDK is the cleanest starting point.

MCP Tool Calling: Real Code Examples and Patterns
Tool calling is the core mechanic of any MCP-powered agent. When the LLM decides it needs to use a tool, it returns a JSON block with the tool name and input parameters. Your code catches that block, executes the matching function, and feeds the result back into the conversation. The two transport patterns you need to know are stdio, used for local development where the client spawns the server as a child process, and Streamable HTTP, used for remote or multi-client deployments. For any new project started in 2026, use Streamable HTTP. The older SSE transport is deprecated.

{ "name": "get_weather", "description": "Returns current weather for a given city", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "Name of the city" } }, "required": ["city"] } }

Common Mistakes and How to Avoid Them
The most common mistake is using stdio transport for a deployment that serves multiple users. Stdio only works for a single local client. If you are building anything beyond a personal tool, switch to Streamable HTTP from day one. The second mistake is writing vague tool descriptions. The model decides which tool to use based entirely on the description you write, so be specific about what each tool does, what inputs it expects, and what it returns. The third mistake is skipping the agentic loop. A single API call is not an agent. You need the loop that checks for tool use and continues until the model returns a final text response.

Conclusion
Building an AI agent with MCP is more approachable than it looks. You define your tools, set up a server, connect an LLM, and run the agentic loop. That is the whole pattern. What MCP adds is a standard so your agent does not need to be rebuilt every time you add a new tool or switch models. With over 13,000 public MCP servers already available, there is a strong chance the tool you need already has an MCP integration ready to go.

If you found this guide useful, Prateek Pareek writes regularly about practical AI development, freelance engineering, and building real products with modern AI tooling. Follow along for more step-by-step breakdowns like this one.

Frequently Asked Questions

What is MCP and why is it used in AI agents?
MCP stands for Model Context Protocol. It is an open standard that lets AI models communicate with external tools, APIs, and data sources using a consistent interface. It is used in AI agents because it eliminates the need to write custom integration code for every tool. Instead, you build one MCP server per tool and any compatible model can use it.

How do I start building an AI agent with MCP in Python?
Install FastMCP and the Anthropic or OpenAI SDK. Create an MCP server, define your tools as decorated Python functions, connect your LLM by passing the tools into the API call, and implement a loop that handles tool use responses. The full step-by-step process is covered in the guide above, with code examples at each stage.

What is the difference between MCP and traditional function calling?
Traditional function calling is a feature baked into specific LLM APIs. Each provider has its own format and your tools are tightly coupled to that provider. MCP is a protocol layer that sits above the LLM. It standardizes how tools are defined, discovered, and called so your tools work with any MCP-compatible model, not just one provider.

Which Python frameworks work best with MCP for building AI agents?
FastMCP is the most straightforward for building MCP servers quickly. LlamaIndex works well when your agent combines tool calling with document retrieval. LangChain is the better choice for complex multi-agent systems or if you need a wide library of pre-built components. For a first project, FastMCP with the Anthropic SDK is the recommended starting point.

Is MCP production-ready for enterprise AI agent deployments?
Yes, as of 2026 MCP is production-ready. The protocol crossed 97 million monthly SDK downloads and has been adopted by major frameworks including LangChain, LlamaIndex, and Google's Agent Development Kit. For enterprise use, you should deploy with Streamable HTTP transport, implement proper authentication, and monitor tool calls with structured logging for auditability