Skip to content

srikanthphalgun/MCP_Demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

1 Commit
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Model Context Protocol (MCP) - AI Math Agent with TextEdit Integration

This project demonstrates a sophisticated AI-powered mathematical problem solver using the Model Context Protocol (MCP). The system consists of an MCP server that provides mathematical tools and TextEdit integration, and an AI client that can autonomously solve complex mathematical problems and visualize results.

๐ŸŽฏ Overview

The system showcases how AI agents can use MCP to:

  • Access a comprehensive suite of mathematical tools
  • Solve complex multi-step problems autonomously
  • Generate visual representations of solutions
  • Integrate with native macOS applications (TextEdit)
  • Handle iterative problem-solving with feedback loops

๐Ÿ—๏ธ Architecture

Core Components

  1. example2.py - MCP Server providing mathematical tools and TextEdit integration
  2. talk2mcp-2.py - AI Client that communicates with the MCP server using Google Gemini

System Flow

AI Client (talk2mcp-2.py) 
    โ†“ (MCP Protocol)
MCP Server (example2.py)
    โ†“ (Tool Execution)
Mathematical Tools + TextEdit Integration
    โ†“ (Results)
AI Client (Processes & Iterates)

๐Ÿ› ๏ธ Features

Mathematical Tools (MCP Server)

  • Basic Operations: Addition, subtraction, multiplication, division
  • Advanced Math: Power, square root, cube root, factorial
  • Trigonometric: Sine, cosine, tangent
  • Logarithmic: Natural logarithm
  • Specialized: Remainder, custom mining function
  • List Operations: Sum of lists, exponential sums
  • Sequences: Fibonacci number generation
  • String Processing: ASCII value extraction

TextEdit Integration

  • Visual Documentation: Create formatted documents with solutions
  • Rectangle Drawing: ASCII art rectangles with dynamic sizing
  • Text Formatting: Professional solution presentation
  • File Management: Automatic temporary file creation and cleanup

AI Agent Capabilities

  • Autonomous Problem Solving: Multi-step mathematical reasoning
  • Tool Discovery: Dynamic exploration of available MCP tools
  • Iterative Processing: Up to 3 iterations with feedback loops
  • Error Handling: Robust error recovery and reporting
  • Timeout Management: Prevents infinite loops with 10-second timeouts

๐Ÿš€ Quick Start

Prerequisites

  • Python 3.8+
  • macOS (for TextEdit integration)
  • Google Generative AI API key

Installation

  1. Install Dependencies:
pip install mcp google-generativeai python-dotenv pillow
  1. Set up API Key:
# Create .env file
echo "GEMINI_API_KEY=your_actual_api_key_here" > .env

Get your API key from: https://aistudio.google.com/app/apikey

Running the System

  1. Start the AI Agent:
python talk2mcp-2.py

The AI will automatically:

  • Connect to the MCP server
  • Discover available tools
  • Solve the mathematical problem
  • Create a visual representation in TextEdit

๐Ÿ“‹ Available Tools

Mathematical Operations

Tool Description Parameters Return Type
add Add two numbers a: int, b: int int
subtract Subtract two numbers a: int, b: int int
multiply Multiply two numbers a: int, b: int int
divide Divide two numbers a: int, b: int float
power Calculate a^b a: int, b: int int
sqrt Square root a: int float
cbrt Cube root a: int float
factorial Factorial of a number a: int int
log Natural logarithm a: int float
remainder Modulo operation a: int, b: int int
sin Sine function a: int float
cos Cosine function a: int float
tan Tangent function a: int float

Advanced Operations

Tool Description Parameters Return Type
add_list Sum all numbers in a list l: list int
strings_to_chars_to_int Get ASCII values of characters string: str list[int]
int_list_to_exponential_sum Sum of exponentials int_list: list float
fibonacci_numbers Generate Fibonacci sequence n: int list
mine Custom mining function a: int, b: int int

TextEdit Integration

Tool Description Parameters Return Type
create_combined_textedit_document Create document with rectangle and solution x1, y1, x2, y2, solution_text dict
open_text_editor Open TextEdit application None dict
draw_rectangle_in_text_editor Draw ASCII rectangle x1, y1, x2, y2 dict
add_text_in_text_editor Add formatted text text: str dict
send_email Send solution via email email_content: str dict

๐Ÿง  AI Agent Behavior

Problem-Solving Process

The AI agent follows this structured approach:

  1. Tool Discovery: Connects to MCP server and retrieves available tools
  2. Problem Analysis: Parses the mathematical problem
  3. Planning: Creates a step-by-step solution plan
  4. Execution: Calls appropriate tools in sequence
  5. Visualization: Creates TextEdit document with results
  6. Iteration: Up to 3 attempts with feedback loops

Example Problem Flow

Problem: "Find the ASCII values of characters in INDIA and then return sum of exponentials of those values. After solving, draw a rectangle in TextEdit to visualize the result."

AI Solution Steps:

  1. strings_to_chars_to_int("INDIA") โ†’ [73, 78, 68, 73, 65]
  2. int_list_to_exponential_sum([73, 78, 68, 73, 65]) โ†’ [result]
  3. create_combined_textedit_document(50, 50, 200, 150, "FINAL_ANSWER: [result]")

Response Format

The AI uses a strict response format:

  • Function Calls: FUNCTION_CALL: function_name|param1|param2|...
  • Final Answers: FINAL_ANSWER: [result]

๐Ÿ”ง Configuration

Timeout Settings

# In talk2mcp-2.py
max_iterations = 3  # Maximum problem-solving iterations
timeout = 10        # LLM response timeout in seconds

Tool Schema Handling

The system automatically converts parameters based on tool schemas:

  • integer โ†’ int()
  • number โ†’ float()
  • array โ†’ list with type conversion
  • string โ†’ str()

๐Ÿ“ File Structure

MCP/
โ”œโ”€โ”€ example2.py              # MCP Server with mathematical tools
โ”œโ”€โ”€ talk2mcp-2.py           # AI Client using Google Gemini
โ”œโ”€โ”€ README.md               # This documentation
โ”œโ”€โ”€ .env                    # Environment variables (create this)
โ””โ”€โ”€ __pycache__/           # Python cache files

๐ŸŽจ TextEdit Integration Details

Dynamic Rectangle Sizing

The system creates proportional rectangles based on coordinates:

display_width = max(10, min(80, width // 5))
display_height = max(3, min(25, height // 10))

Professional Formatting

Solutions are presented with:

  • ASCII art rectangles
  • Centered text
  • Timestamps
  • Auto-generated labels
  • Clean, readable formatting

File Management

  • Automatic temporary file creation
  • TextEdit integration via subprocess
  • Clean file cleanup after display

๐Ÿ› Troubleshooting

Common Issues

  1. "GEMINI_API_KEY not found"

    # Create .env file
    echo "GEMINI_API_KEY=your_key_here" > .env
  2. "No module named mcp"

    pip install mcp
  3. TextEdit not opening

    • Ensure you're on macOS
    • Check TextEdit is installed
    • Verify file permissions
  4. Tool execution errors

    • Check parameter types match tool schemas
    • Verify tool names are correct
    • Review error logs for specific issues

Debug Mode

Enable detailed logging:

# In talk2mcp-2.py, uncomment debug lines
print(f"DEBUG: Raw function info: {function_info}")
print(f"DEBUG: Final arguments: {arguments}")

๐Ÿš€ Advanced Usage

Custom Problem Solving

Modify the query in talk2mcp-2.py:

query = """Your custom mathematical problem here"""

Adding New Tools

In example2.py, add new tools:

@mcp.tool()
def your_new_tool(param1: int, param2: str) -> float:
    """Your tool description"""
    return your_calculation(param1, param2)

Customizing AI Behavior

Modify the system prompt in talk2mcp-2.py:

system_prompt = f"""Your custom AI instructions..."""

๐Ÿ”ฎ Future Enhancements

  • Multi-Platform Support: Windows and Linux compatibility
  • Enhanced Visualization: More drawing tools and shapes
  • Advanced Math: Matrix operations, calculus functions
  • Real-time Collaboration: Multiple AI agents working together
  • Voice Integration: Speech-to-text problem input
  • Web Interface: Browser-based problem solving

๐Ÿ“Š Performance

  • Response Time: ~2-5 seconds per tool call
  • Accuracy: High mathematical precision
  • Reliability: Robust error handling and recovery
  • Scalability: Supports complex multi-step problems

๐Ÿ“ License

This project is for educational and demonstration purposes, showcasing the power of Model Context Protocol for AI agent development.

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add your enhancements
  4. Test thoroughly
  5. Submit a pull request

๐Ÿ“ž Support

For issues and questions:

  • Check the troubleshooting section
  • Review the debug output
  • Examine the MCP server logs
  • Verify your API key configuration

Built with โค๏ธ using Model Context Protocol and Google Gemini AI

About

Model Context Protocol learning and Demo

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages