kfr3
MCP Serverkfr3public

mcp_project

包含模型上下文协议 (MCP) 的示例和演示,用于标准化大型语言模型的上下文提供。

Repository Info

0
Stars
0
Forks
0
Watchers
0
Issues
Python
Language
-
License

About This Server

包含模型上下文协议 (MCP) 的示例和演示,用于标准化大型语言模型的上下文提供。

Model Context Protocol (MCP) - This server can be integrated with AI applications to provide additional context and capabilities, enabling enhanced AI interactions and functionality.

Documentation

Model Context Protocol (MCP) Demo

This repository contains examples and demonstrations of the Model Context Protocol (MCP), a standardized way for applications to provide context to Large Language Models (LLMs).

Table of Contents

  • Introduction
  • Project Structure
  • MCP Core Concepts
  • Simple MCP Server Example
  • Testing MCP Servers
  • MCP Inspector Configuration
  • Advanced Usage
  • Best Practices

Introduction

The Model Context Protocol (MCP) provides a standardized way for applications to expose data and functionality to Large Language Models (LLMs). It separates the concerns of providing context from the actual LLM interaction, allowing developers to build more modular, maintainable, and secure AI-powered applications.

MCP is designed with a clear separation of concerns:

  • Resources: Provide data to LLMs
  • Tools: Provide functionality that LLMs can invoke
  • Prompts: Define reusable interaction patterns

Project Structure

mcp_demo/
├── docs/                 # Documentation files
│   ├── mcp_tutorial.md   # Comprehensive MCP tutorial
│   └── mcp_config.png    # MCP Inspector configuration screenshot
├── references/           # Reference implementations
│   └── python-sdk/       # MCP Python SDK reference
├── src/                  # Source code examples
│   └── basic_demo.py     # Basic MCP example
├── simple_mcp_server.py  # Simple MCP server implementation
├── test_mcp_client.py    # Client for testing MCP servers
└── README.md             # This file

MCP Core Concepts

1. Server

The MCP server is the main component that exposes your data and functionality to LLM applications. It handles connection management, protocol compliance, message routing, and lifecycle events.

2. Resources

Resources provide data to LLMs (similar to GET endpoints in REST APIs). They allow LLMs to access information from your application or external sources.

  • Have a URI-like structure (resource://path)
  • Can support path parameters (users://{user_id})
  • Return structured data that gets injected into the LLM's context

3. Tools

Tools provide functionality that LLMs can invoke (similar to POST endpoints in REST APIs). They allow LLMs to perform operations and produce side effects.

  • Have a name and schema defining their inputs
  • Execute code in your application environment
  • Return results back to the LLM

4. Prompts

Prompts define reusable interaction patterns for LLMs.

  • Can be parameterized with dynamic data
  • Provide consistent interaction templates
  • Help enforce application-specific behaviors

Simple MCP Server Example

The simple_mcp_server.py provides a minimal implementation of an MCP server with examples of all three core components:

Resource Example

@mcp.resource("greeting://{name}")
def greeting_resource(name: str) -> str:
    """Get a personalized greeting
    
    Args:
        name: The name to include in the greeting
    """
    return f"Hello, {name}! Welcome to MCP."

This resource accepts a name parameter and returns a personalized greeting. It demonstrates how to create a parameterized resource with a URI pattern.

Tool Example

@mcp.tool()
def calculate(operation: str, a: float, b: float) -> float:
    """Perform a simple calculation
    
    Args:
        operation: The operation to perform (add, subtract, multiply, divide)
        a: First number
        b: Second number
    """
    if operation == "add":
        return a + b
    elif operation == "subtract":
        return a - b
    elif operation == "multiply":
        return a * b
    elif operation == "divide":
        if b == 0:
            raise ValueError("Cannot divide by zero")
        return a / b
    else:
        raise ValueError(f"Unknown operation: {operation}")

This tool performs basic arithmetic operations. It demonstrates how to create a tool with multiple parameters and error handling.

Prompt Example

@mcp.prompt()
def assistant_prompt() -> str:
    """Provide a template for the assistant's behavior"""
    return """
    You are a helpful assistant with calculation abilities.
    You can calculate using the following operations:
    - Addition
    - Subtraction
    - Multiplication
    - Division
    
    When performing calculations, show your work clearly.
    """

This prompt provides a template for assistant behavior. It demonstrates how to define a reusable prompt that guides LLM interactions.

Testing MCP Servers

There are two main ways to test MCP servers:

1. Using the Test Client (test_mcp_client.py)

The test_mcp_client.py file provides a simple client that connects to the MCP server and tests its functionality:

# Connect to MCP server
async with stdio_client(
    StdioServerParameters(command="python", args=["simple_mcp_server.py"])
) as (read, write):
    # Create client session
    async with ClientSession(read, write) as session:
        # Initialize session
        await session.initialize()
        
        # Test tool
        calc_result = await session.call_tool("calculate", {
            "operation": "add",
            "a": 10,
            "b": 5
        })
        print(f"10 + 5 = {calc_result}")
        
        # Test prompt
        prompt_result = await session.get_prompt("assistant_prompt")

To run the test client:

python test_mcp_client.py

2. Using the MCP Inspector

The MCP Inspector provides a web interface for testing MCP servers. To launch the inspector:

mcp dev simple_mcp_server.py

This opens a web interface at http://127.0.0.1:6274 where you can interact with your MCP server.

MCP Inspector Configuration

When using the MCP Inspector, you need to configure the connection to your MCP server:

!MCP Inspector Configuration

  • Transport Type: Select "STDIO"
  • Command: Enter "python"
  • Arguments: Enter "simple_mcp_server.py"

Once connected, you can:

  • View and test tools
  • Access resources
  • View prompts

Advanced Usage

Integrating with Web Frameworks

You can integrate MCP with existing web frameworks like FastAPI:

from fastapi import FastAPI
from mcp.server.fastmcp import FastMCP

# Create MCP server
mcp = FastMCP("My MCP Server")
# Define resources, tools, and prompts...

# Create FastAPI app
app = FastAPI()

# Mount MCP server
app.mount("/mcp", mcp.sse_app())

Claude Desktop Integration

To use your MCP server with Claude Desktop:

mcp install simple_mcp_server.py

This registers your server with Claude Desktop, making it available for use in conversations.

Best Practices

Following enterprise application development principles:

1. Reliability First

  • Implement robust error handling in MCP tools
  • Use type hints for schema validation
  • Test all components thoroughly

2. Clean Implementation

  • Organize MCP components by domain
  • Follow consistent naming conventions
  • Document all components with comprehensive docstrings

3. Industry Best Practices

  • Follow RESTful patterns for resources
  • Implement proper validation for inputs
  • Return consistent, well-structured responses

4. Systems Thinking

  • Consider the entire workflow from LLM to backend systems
  • Design clear interfaces between components
  • Use proper encapsulation to prevent unintended side effects

5. Security Considerations

  • Validate all inputs rigorously
  • Implement proper authorization checks
  • Limit sensitive operations
  • Log security-relevant events

Quick Start

1

Clone the repository

git clone https://github.com/kfr3/mcp_project
2

Install dependencies

cd mcp_project
npm install
3

Follow the documentation

Check the repository's README.md file for specific installation and usage instructions.

Repository Details

Ownerkfr3
Repomcp_project
LanguagePython
License-
Last fetched8/10/2025

Recommended MCP Servers

💬

Discord MCP

Enable AI assistants to seamlessly interact with Discord servers, channels, and messages.

integrationsdiscordchat
🔗

Knit MCP

Connect AI agents to 200+ SaaS applications and automate workflows.

integrationsautomationsaas
🕷️

Apify MCP Server

Deploy and interact with Apify actors for web scraping and data extraction.

apifycrawlerdata
🌐

BrowserStack MCP

BrowserStack MCP Server for automated testing across multiple browsers.

testingqabrowsers

Zapier MCP

A Zapier server that provides automation capabilities for various apps.

zapierautomation