THE SUMMARYAI-generated
MCP Server for AI Agents: A Deep Dive
Key Concepts:
- MCP (Model Context Protocol): A protocol for defining and reusing tools across different AI agent frameworks.
- MCP Server: A server that hosts tools, prompts, and resources accessible via the MCP protocol.
- Tools: Python functions wrapped with the
@mcp_tooldecorator, providing specific functionalities (e.g., fetching stock prices). - Prompts: Pre-defined text templates stored on the server and accessible via the
@mcp_promptdecorator. - Resources: Data sources (e.g., vector databases) made available to clients through the
@mcp_resourcedecorator. - Small Agents: A lightweight agent library from Hugging Face used for demonstration.
- Langflow: A visual programming tool for building LLM applications.
- Cursor: An AI-powered code editor.
- Standard Input/Output (stdio): A transport mode for communication between the agent and the MCP server.
- Server-Sent Events (SSE): An alternative transport mode for communication between the agent and the MCP server.
- YFinance: A Python library to get data from Yahoo Finance.
- Colorama: A Python library to add color to terminal output.
- Chroma DB: A vector database.
1. Building the MCP Server
- Core Idea: Wrap existing Python functions into an MCP server to expose them as tools for AI agents.
- Step-by-Step Process:
- Define a Python function: Create a function that performs the desired task (e.g.,
get_stock_price(stock_ticker)usingyfinance).- Example:
import yfinance as yf import colorama from colorama import Fore, Style def get_stock_price(stock_ticker): ticker = yf.Ticker(stock_ticker) data = ticker.history(period="1mo") close_prices = data['Close'] print(Fore.GREEN + str(close_prices) + Style.RESET_ALL)
- Example:
- Import
FastMCP: Import theFastMCPclass from themcpSDK. - Create a server instance: Instantiate a
FastMCPserver (e.g.,yfinance_server = FastMCP()). - Decorate functions with
@mcp_tool: Use the@mcp_tooldecorator to expose Python functions as tools.- Add a docstring to explain the tool's purpose and usage to the agent.
- Example:
from mcp import FastMCP, mcp_tool server = FastMCP() @server.tool def stock_price(stock_ticker: str): """ Gets the stock price for a given ticker. """ ticker = yf.Ticker(stock_ticker) data = ticker.history(period="1mo") close_prices = data['Close'] return str(close_prices)
- Run the server: Use
mcp.run(transport="stdio")to start the server using standard input/output.- Example:
if __name__ == "__main__": server.run(transport="stdio")
- Example:
- Define a Python function: Create a function that performs the desired task (e.g.,
- Technical Details:
- The
@mcp_tooldecorator registers the function with the MCP server, making it discoverable by agents. - The docstring is crucial for the agent to understand how to use the tool.
- The
stock_ticker: strannotation specifies the expected input type.
- The
- Testing with MCP Dev:
- Use the command
uvuv mcpdev server.pyto start the MCP development server. - The MCP development server provides a visual inspector to test the tools.
- The inspector allows you to connect to the server, list available tools, and run them with sample inputs.
- Use the command
2. Connecting to an Agent (Small Agents)
- Objective: Integrate the MCP server with an AI agent to enable it to use the defined tools.
- Library Used:
small_agentsfrom Hugging Face. - Step-by-Step Process:
- Import necessary modules: Import
ToolCallingAgent,ToolCollection,LightLLM, andStdIOServerParametersfromsmall_agentsandmcp. - Instantiate a LightLLM model: Create an instance of
LightLLMwith a specified model ID (e.g., an O llama model) and context size.- Example:
llm = LightLLM(model_id="llama2:7b", context_size=8192)
- Example:
- Configure stdio server parameters: Define the command to run the MCP server using
StdIOServerParameters.- Example:
server_params = StdIOServerParameters(command="uvuv server.py")
- Example:
- Create a tool collection: Use
ToolCollection.mcpto create a tool collection from the MCP server parameters.- Example:
tools = ToolCollection.mcp(server_params)
- Example:
- Create a ToolCallingAgent: Instantiate a
ToolCallingAgentwith the tool collection and theLightLLMmodel.- Example:
agent = ToolCallingAgent(tools=tools, llm=llm)
- Example:
- Run a prompt: Use
agent.run(prompt)to execute a prompt and trigger the agent to use the MCP tools.- Example:
response = agent.run("What was IBM's last stock price?")
- Example:
- Import necessary modules: Import
- Key Points:
- The
StdIOServerParametersobject specifies how to start the MCP server. - The
ToolCollection.mcpmethod retrieves the available tools from the MCP server. - The
ToolCallingAgentorchestrates the interaction between the LLM and the tools.
- The
3. Connecting to Other Capabilities (Cursor, Langflow)
- Cursor Integration:
- Open Cursor settings and navigate to the MCP section.
- Add a new global MCP server.
- Configure the command to run the MCP server (e.g.,
uvuv server.py) and the directory where the server file is located. - Use the agent mode in Cursor and ask prompts that trigger the MCP tools.
- Langflow Integration:
- Add an MCP Server component to the Langflow flow.
- Enable tool mode on the MCP Server component.
- Configure the MCP command with the same command used in other integrations.
- Connect the MCP Server tool set to the tool node inside the agent.
- Run the Langflow flow and test the integration.
4. Expanding the MCP Server with More Tools
- Adding Stock Info Tool:
- Create a new function
stock_info(stock_ticker: str)to retrieve company information from Yahoo Finance. - Decorate the function with
@mcp_tool. - Include a docstring explaining the tool's purpose.
- Create a new function
- Adding Income Statement Tool:
- Create a new function
income_statement(stock_ticker: str)to retrieve the income statement from Yahoo Finance. - Decorate the function with
@mcp_tool. - Include a docstring explaining the tool's purpose.
- Create a new function
5. Other MCP Capabilities: Prompts and Resources
- Prompts:
- Use the
@mcp_promptdecorator to define prompts on the server. - Create a function that takes input data and formats it into a prompt template.
- Example:
from mcp import FastMCP, mcp_prompt server = FastMCP() @server.prompt def stock_summary(stock_data: str): """ Generates a summary of stock data. """ prompt_template = f"You are a helpful financial assistant designed to summarize stock data. Here is the stock data: {stock_data}" return prompt_template - The MCP inspector allows you to test the prompts by providing sample data and retrieving the formatted prompt.
- Use the
- Resources:
- Use the
@mcp_resourcedecorator to expose data sources (e.g., databases) as resources. - Create a function that queries the data source and returns the results.
- Example (using Chroma DB):
from mcp import FastMCP, mcp_resource import chromadb server = FastMCP() client = chromadb.PersistentClient(path="TickerDB") collection = client.get_collection("stock_tickers") @server.resource def list_tickers(search_term: str): """ Searches for a stock ticker in the database. """ results = collection.query(query_texts=[search_term], n_results=1) return str(results) - The MCP inspector allows you to search for resources and retrieve the data.
- Use the
Conclusion
The video demonstrates how to build an MCP server to expose tools, prompts, and resources to AI agents. It covers the core concepts of MCP, the step-by-step process of building a server, connecting it to different agent frameworks (Small Agents, Cursor, Langflow), and expanding its capabilities with additional tools, prompts, and resources. The MCP protocol provides a standardized way to define and reuse tools across different AI agent frameworks, reducing code duplication and improving maintainability.
AI summaries can miss context or contain errors. Check important details against the original video.