phil71x commited on
Commit
926a662
·
1 Parent(s): aee07bb

docs: Add comprehensive guide for creating MCP tools with Gradio and Python

Browse files
Files changed (1) hide show
  1. docs/mcp_with_gradio.md +143 -0
docs/mcp_with_gradio.md ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Creating MCP Tools with Gradio and Python
2
+
3
+ This document provides a detailed explanation of how to build a Model Context Protocol (MCP) tool server using Python and Gradio. We will use a simple sentiment analysis function as a practical example to illustrate the process of exposing Python functions as MCP tools.
4
+
5
+ ## 1. Project Overview
6
+
7
+ This project demonstrates how to build a Model Context Protocol (MCP) tool server using Python and Gradio. We will use a simple sentiment analysis function as a practical example to illustrate the process of exposing Python functions as MCP tools.
8
+
9
+ The primary focus is to show how Gradio can automatically create an MCP tool from a Python function, making it accessible to MCP clients like LLM-based agents. The sentiment analysis function serves as a concrete illustration of this capability, rather than being the central subject itself.
10
+
11
+ ## 2. Core Technologies
12
+
13
+ ### a. Python
14
+ The project is written in Python, a versatile and widely-used programming language, particularly popular in web development, data science, and machine learning.
15
+
16
+ ### b. Gradio
17
+ [Gradio](https://www.gradio.app/) is a Python library that makes it easy to create and share web-based UIs for machine learning models, Python functions, or any arbitrary Python code. Key features relevant to this project include:
18
+ * **Rapid UI Development**: Quickly build interactive demos.
19
+ * **Variety of Input/Output Components**: Supports text boxes, sliders, images, JSON, etc.
20
+ * **Automatic MCP Server Integration**: Can automatically expose Python functions as MCP tools, which is the core focus of this demonstration.
21
+
22
+ ### c. Model Context Protocol (MCP)
23
+ [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) is a standard designed to allow language models (LLMs) and other AI agents to interact with external tools and resources in a structured way.
24
+ Key concepts of MCP include:
25
+ * **Resources**: File-like data that can be read by clients (e.g., API responses, file contents).
26
+ * **Tools**: Functions (like our example sentiment analysis function) that can be called by an LLM or agent (with user approval) to perform actions or retrieve information.
27
+ * **Prompts**: Pre-written templates that help users accomplish specific tasks with an LLM.
28
+
29
+ #### Gradio MCP Integration
30
+ Gradio simplifies the creation of MCP servers by:
31
+ 1. **Automatic Tool Conversion**: Python functions provided to a Gradio Interface are automatically converted into MCP Tools.
32
+ 2. **Schema Mapping**: Input components (like `gr.Textbox`) are mapped to the tool's argument schemas. Docstrings and type hints in the Python function further refine this schema.
33
+ 3. **Response Formatting**: Output components (like `gr.JSON`) determine the response format of the MCP tool.
34
+ 4. **Communication Protocol**: Sets up JSON-RPC over HTTP+SSE (Server-Sent Events) for client-server communication.
35
+ 5. **Dual Endpoints**: Creates both a user-facing web interface and an MCP server endpoint from the same Python function.
36
+
37
+ ### d. TextBlob (for the example function)
38
+ [TextBlob](https://textblob.readthedocs.io/) is a Python library for processing textual data. In this project, we use it *solely to provide a simple example function* for sentiment analysis. Its specific NLP capabilities are secondary to its role as an illustrative function to be exposed via MCP.
39
+
40
+ ## 3. Code Breakdown (`server.py`)
41
+
42
+ Let's examine the `server.py` file. The core idea is to define a Python function and then use Gradio to expose it as an MCP tool.
43
+
44
+ ```python
45
+ import gradio as gr
46
+ from textblob import TextBlob # For our example function
47
+ ```
48
+ * **`import gradio as gr`**: Imports the Gradio library.
49
+ * **`from textblob import TextBlob`**: Imports `TextBlob` for our example `sentiment_analysis` function.
50
+
51
+ ```python
52
+ # This is the example Python function we will expose as an MCP tool.
53
+ def sentiment_analysis(text: str) -> dict:
54
+ """
55
+ Analyze the sentiment of the given text.
56
+ (This docstring is used by Gradio for the MCP tool description)
57
+
58
+ Args:
59
+ text (str): The text to analyze (used for MCP tool input schema)
60
+
61
+ Returns:
62
+ dict: A dictionary containing polarity, subjectivity, and assessment (used for MCP tool output schema)
63
+ """
64
+ # The internal logic of this function is an example.
65
+ # Any Python function can be exposed similarly.
66
+ blob = TextBlob(text)
67
+ sentiment = blob.sentiment
68
+
69
+ return {
70
+ "polarity": round(sentiment.polarity, 2),
71
+ "subjectivity": round(sentiment.subjectivity, 2),
72
+ "assessment": "positive"
73
+ if sentiment.polarity > 0
74
+ else "negative"
75
+ if sentiment.polarity < 0
76
+ else "neutral",
77
+ }
78
+ ```
79
+ * **`def sentiment_analysis(text: str) -> dict:`**: Defines our example function.
80
+ * **`text: str` (Type Hint)**: Gradio uses this (along with the input component) to define the MCP tool's input argument type and schema.
81
+ * **`-> dict` (Return Type Hint)**: Gradio uses this (along with the output component) for the MCP tool's output schema.
82
+ * **Docstring**: Crucially, Gradio uses the docstring to generate the description for the MCP tool, its arguments (`Args`), and what it returns (`Returns`). This makes the tool understandable to MCP clients.
83
+ * The internal logic using `TextBlob` is specific to this example. The key is that *any* well-documented Python function with type hints can be similarly exposed by Gradio.
84
+
85
+ ```python
86
+ # Create the Gradio interface to expose the function
87
+ demo = gr.Interface(
88
+ fn=sentiment_analysis, # The Python function to expose as an MCP tool
89
+ inputs=gr.Textbox(placeholder="Enter text to analyze..."), # Defines UI and helps MCP schema
90
+ outputs=gr.JSON(), # Defines UI output and MCP tool output type
91
+ title="MCP Tool Server Example (Sentiment Analysis)",
92
+ description="Demonstrates exposing a Python function as an MCP tool via Gradio.",
93
+ )
94
+ ```
95
+ * **`demo = gr.Interface(...)`**: Creates a Gradio Interface.
96
+ * **`fn=sentiment_analysis`**: Specifies the Python function that Gradio will wrap and expose as an MCP tool.
97
+ * **`inputs=gr.Textbox(...)`**: Defines the input component for the optional web UI and helps Gradio infer the input schema for the MCP tool (expecting a string for the `text` argument).
98
+ * **`outputs=gr.JSON()`**: Defines the output component for the web UI and signals to Gradio that the MCP tool will return a JSON structure (matching the `dict` return type).
99
+
100
+ ```python
101
+ # Launch the interface and the MCP server
102
+ if __name__ == "__main__":
103
+ demo.launch(mcp_server=True) # Key parameter to enable MCP
104
+ ```
105
+ * **`demo.launch(mcp_server=True)`**: This launches the Gradio web UI and, most importantly for this demonstration, starts the MCP server.
106
+ * **`mcp_server=True`**: This parameter explicitly tells Gradio to expose the function (`sentiment_analysis`) defined in `gr.Interface` as an MCP tool.
107
+
108
+ ## 4. Running the Server
109
+
110
+ To start the server:
111
+ 1. Open your terminal or command prompt.
112
+ 2. Navigate to the directory containing `server.py`.
113
+ 3. Ensure you have the necessary libraries installed (`pip install gradio textblob`).
114
+ 4. Run the command: `python server.py`
115
+
116
+ Upon successful execution, you will see output similar to:
117
+ ```
118
+ Running on local URL: http://127.0.0.1:7860
119
+ Running on MCP server at: http://127.0.0.1:7860/gradio_api/mcp/sse
120
+ ```
121
+ * **Web Interface**: An optional web UI is available at `http://127.0.0.1:7860`.
122
+ * **MCP Server Endpoint**: The MCP server, exposing the `sentiment_analysis` function as a tool, is available at `http://127.0.0.1:7860/gradio_api/mcp/sse`. MCP clients connect here.
123
+
124
+ ## 5. How Gradio Exposes Functions as MCP Tools (Illustrated by the Example)
125
+
126
+ 1. **Tool Creation**: When `demo.launch(mcp_server=True)` is called, Gradio inspects the Python function (in this case, `sentiment_analysis`) provided to `gr.Interface`.
127
+ 2. **Schema Generation**: Gradio automatically generates the MCP tool's schema:
128
+ * The Python function's name (`sentiment_analysis`) becomes the MCP tool's name.
129
+ * The function's docstring is used for the tool's description, arguments, and return value explanations.
130
+ * Input components (e.g., `gr.Textbox`) and Python type hints (e.g., `text: str`) define the tool's input arguments and their types.
131
+ * Output components (e.g., `gr.JSON()`) and Python return type hints (e.g., `-> dict`) define the tool's output structure and type.
132
+ 3. **Server Endpoint**: Gradio hosts an HTTP server that listens for MCP requests at the `/gradio_api/mcp/sse` path. Communication typically uses JSON-RPC over HTTP with Server-Sent Events (SSE).
133
+ 4. **Client Interaction**: An MCP client can:
134
+ * Connect to the MCP server endpoint.
135
+ * Request a list of available tools (it would find `sentiment_analysis` with its generated schema).
136
+ * Call the tool by sending a request matching the schema (e.g., providing a string for the `text` argument).
137
+ * Receive the JSON response as defined by the tool's output schema.
138
+
139
+ ## 6. Conclusion
140
+
141
+ This project primarily demonstrates the ease with which Python functions can be exposed as Model Context Protocol (MCP) tools using Gradio. The sentiment analysis function served as a straightforward example to illustrate this process.
142
+
143
+ The key takeaway is Gradio's capability to automatically handle MCP tool creation, schema generation from docstrings and type hints, and server endpoint setup. This significantly simplifies the development of MCP-compatible services, allowing developers to focus on their core Python logic while Gradio manages the MCP integration. Any Python function can be similarly exposed, making Gradio a powerful utility for extending the capabilities of LLMs and other AI agents through MCP.