text
stringlengths
0
2k
heading1
stringlengths
3
79
source_page_url
stringclasses
189 values
source_page_title
stringclasses
189 values
Another type of data persistence Gradio supports is session state, where data persists across multiple submits within a page session. However, data is _not_ shared between different users of your model. To store data in a session state, you need to do three things: 1. Pass in an extra parameter into your function, whi...
Session State
https://gradio.app/guides/interface-state
Building Interfaces - Interface State Guide
Gradio includes more than 30 pre-built components (as well as many [community-built _custom components_](https://www.gradio.app/custom-components/gallery)) that can be used as inputs or outputs in your demo. These components correspond to common data types in machine learning and data science, e.g. the `gr.Image` compo...
Gradio Components
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
We used the default versions of the `gr.Textbox` and `gr.Slider`, but what if you want to change how the UI components look or behave? Let's say you want to customize the slider to have values from 1 to 10, with a default of 2. And you wanted to customize the output text field — you want it to be larger and have a lab...
Components Attributes
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
Suppose you had a more complex function, with multiple outputs as well. In the example below, we define a function that takes a string, boolean, and number, and returns a string and number. $code_hello_world_3 $demo_hello_world_3 Just as each component in the `inputs` list corresponds to one of the parameters of the...
Multiple Input and Output Components
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
Gradio supports many types of components, such as `Image`, `DataFrame`, `Video`, or `Label`. Let's try an image-to-image function to get a feel for these! $code_sepia_filter $demo_sepia_filter When using the `Image` component as input, your function will receive a NumPy array with the shape `(height, width, 3)`, wher...
An Image Example
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
You can provide example data that a user can easily load into `Interface`. This can be helpful to demonstrate the types of inputs the model expects, as well as to provide a way to explore your dataset in conjunction with your model. To load example data, you can provide a **nested list** to the `examples=` keyword argu...
Example Inputs
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
In the previous example, you may have noticed the `title=` and `description=` keyword arguments in the `Interface` constructor that helps users understand your app. There are three arguments in the `Interface` constructor to specify where this content should go: - `title`: which accepts text and can display it at the...
Descriptive Content
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
If your prediction function takes many inputs, you may want to hide some of them within a collapsed accordion to avoid cluttering the UI. The `Interface` class takes an `additional_inputs` argument which is similar to `inputs` but any input components included here are not visible by default. The user must click on the...
Additional Inputs within an Accordion
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
The Model Context Protocol (MCP) standardizes how applications provide context to LLMs. It allows Claude to interact with external tools, like image generators, file systems, or APIs, etc.
What is MCP?
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
- Python 3.10+ - An Anthropic API key - Basic understanding of Python programming
Prerequisites
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
First, install the required packages: ```bash pip install gradio anthropic mcp ``` Create a `.env` file in your project directory and add your Anthropic API key: ``` ANTHROPIC_API_KEY=your_api_key_here ```
Setup
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
The server provides tools that Claude can use. In this example, we'll create a server that generates images through [a HuggingFace space](https://huggingface.co/spaces/ysharma/SanaSprint). Create a file named `gradio_mcp_server.py`: ```python from mcp.server.fastmcp import FastMCP import json import sys import io imp...
Part 1: Building the MCP Server
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
"message": f"Error generating image: {str(e)}" }) if __name__ == "__main__": mcp.run(transport='stdio') ``` What this server does: 1. It creates an MCP server that exposes a `generate_image` tool 2. The tool connects to the SanaSprint model hosted on HuggingFace Spaces 3. It handles the asynchronous na...
Part 1: Building the MCP Server
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
Now let's create a Gradio chat interface as MCP Client that connects Claude to our MCP server. Create a file named `app.py`: ```python import asyncio import os import json from typing import List, Dict, Any, Union from contextlib import AsyncExitStack import gradio as gr from gradio.components.chatbot import ChatMes...
Part 2: Building the MCP Client with Gradio
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
iption, "input_schema": tool.inputSchema } for tool in response.tools] tool_names = [tool["name"] for tool in self.tools] return f"Connected to MCP server. Available tools: {', '.join(tool_names)}" def process_message(self, message: str, history: List[Union[Dict[str...
Part 2: Building the MCP Client with Gradio
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
ntent": content.text }) elif content.type == 'tool_use': tool_name = content.name tool_args = content.input result_messages.append({ "role": "assistant", "content": f"I'l...
Part 2: Building the MCP Client with Gradio
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
}) result_content = result.content if isinstance(result_content, list): result_content = "\n".join(str(item) for item in result_content) try: result_json = json.loads(result_content) ...
Part 2: Building the MCP Client with Gradio
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
"parent_id": f"result_{tool_name}", "id": f"raw_result_{tool_name}", "title": "Raw Output" } }) claude_messages.append({"role": "user", "content": f"Tool result for {tool_name}: {result_...
Part 2: Building the MCP Client with Gradio
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
w(equal_height=True): msg = gr.Textbox( label="Your Question", placeholder="Ask about weather or alerts (e.g., What's the weather in New York?)", scale=4 ) clear_btn = gr.Button("Clear Chat", scale=1) connect_btn.click(...
Part 2: Building the MCP Client with Gradio
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
To run your MCP application: - Start a terminal window and run the MCP Client: ```bash python app.py ``` - Open the Gradio interface at the URL shown (typically http://127.0.0.1:7860) - In the Gradio interface, you'll see a field for the MCP Server path. It should default to `gradio_mcp_server.py`. - Click "C...
Running the Application
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
Now you can chat with Claude and it will be able to generate images based on your descriptions. Try prompts like: - "Can you generate an image of a mountain landscape at sunset?" - "Create an image of a cool tabby cat" - "Generate a picture of a panda wearing sunglasses" Claude will recognize these as image generatio...
Example Usage
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
Here's the high-level flow of what happens during a chat session: 1. Your prompt enters the Gradio interface 2. The client forwards your prompt to Claude 3. Claude analyzes the prompt and decides to use the `generate_image` tool 4. The client sends the tool call to the MCP server 5. The server calls the external image...
How it Works
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
Now that you have a working MCP system, here are some ideas to extend it: - Add more tools to your server - Improve error handling - Add private Huggingface Spaces with authentication for secure tool access - Create custom tools that connect to your own APIs or services - Implement streaming responses for better user...
Next Steps
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
Congratulations! You've successfully built an MCP Client and Server that allows Claude to generate images based on text prompts. This is just the beginning of what you can do with Gradio and MCP. This guide enables you to build complex AI applications that can use Claude or any other powerful LLM to interact with virtu...
Conclusion
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio Guide
As of version 5.36.0, Gradio now comes with a built-in MCP server that can upload files to a running Gradio application. In the `View API` page of the server, you should see the following code snippet if any of the tools require file inputs: <img src="https://huggingface.co/datasets/freddyaboulton/bucket/resolve/main/...
Using the File Upload MCP Server
https://gradio.app/guides/file-upload-mcp
Mcp - File Upload Mcp Guide
In this guide, we've covered how you can connect to the Upload File MCP Server so that your agent can upload files before using Gradio MCP servers. Remember to set the `<UPLOAD_DIRECTORY>` as small as possible to prevent unintended file uploads!
Conclusion
https://gradio.app/guides/file-upload-mcp
Mcp - File Upload Mcp Guide
If you're using LLMs in your workflow, adding this server will augment them with just the right context on gradio - which makes your experience a lot faster and smoother. <video src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/mcp-docs.mp4" style="width:100%" controls p...
Why an MCP Server?
https://gradio.app/guides/using-docs-mcp
Mcp - Using Docs Mcp Guide
For clients that support streamable HTTP (e.g. Cursor, Windsurf, Cline), simply add the following configuration to your MCP config: ```json { "mcpServers": { "gradio": { "url": "https://gradio-docs-mcp.hf.space/gradio_api/mcp/" } } } ``` We've included step-by-step instructions for Cursor below, but...
Installing in the Clients
https://gradio.app/guides/using-docs-mcp
Mcp - Using Docs Mcp Guide
There are currently only two tools in the server: `gradio_docs_mcp_load_gradio_docs` and `gradio_docs_mcp_search_gradio_docs`. 1. `gradio_docs_mcp_load_gradio_docs`: This tool takes no arguments and will load an /llms.txt style summary of Gradio's latest, full documentation. Very useful context the LLM can parse befo...
Tools
https://gradio.app/guides/using-docs-mcp
Mcp - Using Docs Mcp Guide
An MCP (Model Control Protocol) server is a standardized way to expose tools so that they can be used by LLMs. A tool can provide an LLM functionality that it does not have natively, such as the ability to generate images or calculate the prime factors of a number.
What is an MCP Server?
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
LLMs are famously not great at counting the number of letters in a word (e.g. the number of "r"-s in "strawberry"). But what if we equip them with a tool to help? Let's start by writing a simple Gradio app that counts the number of letters in a word or phrase: $code_letter_counter Notice that we have: (1) included a ...
Example: Counting Letters in a Word
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
1. **Tool Conversion**: Each API endpoint in your Gradio app is automatically converted into an MCP tool with a corresponding name, description, and input schema. To view the tools and schemas, visit http://your-server:port/gradio_api/mcp/schema or go to the "View API" link in the footer of your Gradio app, and then cl...
Key features of the Gradio <> MCP Integration
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
p: To minimize latency and increase throughput by as much as 10 times, set queue=False in the event handlers of your Gradio app. However, this disables progress notifications so its recommended that long running events set queue=True
Key features of the Gradio <> MCP Integration
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
If there's an existing Space that you'd like to use an MCP server, you'll need to do three things: 1. First, [duplicate the Space](https://huggingface.co/docs/hub/en/spaces-more-ways-to-createduplicating-a-space) if it is not your own Space. This will allow you to make changes to the app. If the Space requires a GPU, ...
Converting an Existing Space
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
You can use either a public Space or a private Space as an MCP server. If you'd like to use a private Space as an MCP server (or a ZeroGPU Space with your own quota), then you will need to provide your [Hugging Face token](https://huggingface.co/settings/token) when you make your request. To do this, simply add it as a...
Private Spaces
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
You may wish to authenticate users more precisely or let them provide other kinds of credentials or tokens in order to provide a custom experience for different users. Gradio allows you to access the underlying `starlette.Request` that has made the tool call, which means that you can access headers, originating IP ad...
Authentication and Credentials
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
the headers you need to supply when connecting to the server! See the image below: ```python import gradio as gr def make_api_request_on_behalf_of_user(prompt: str, x_api_token: gr.Header): """Make a request to everyone's favorite API. Args: prompt: The prompt to send to the API. Returns: ...
Authentication and Credentials
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
Gradio automatically sets the tool name based on the name of your function, and the description from the docstring of your function. But you may want to change how the description appears to your LLM. You can do this by using the `api_description` parameter in `Interface`, `ChatInterface`, or any event listener. This p...
Modifying Tool Descriptions
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
In addition to tools (which execute functions generally and are the default for any function exposed through the Gradio MCP integration), MCP supports two other important primitives: **resources** (for exposing data) and **prompts** (for defining reusable templates). Gradio provides decorators to easily create MCP serv...
MCP Resources and Prompts
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
So far, all of our MCP tools, resources, or prompts have corresponded to event listeners in the UI. This works well for functions that directly update the UI, but may not work if you wish to expose a "pure logic" function that should return raw data (e.g. a JSON object) without directly causing a UI update. In order t...
Adding MCP-Only Functions
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
In some cases, you may decide not to use Gradio's built-in integration and instead manually create an FastMCP Server that calls a Gradio app. This approach is useful when you want to: - Store state / identify users between calls instead of treating every tool call completely independently - Start the Gradio app MCP se...
Gradio with FastMCP
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
return result @mcp.tool() async def run_dia_tts(prompt: str, space_id: str = "ysharma/Dia-1.6B") -> str: """Text-to-Speech Synthesis. Args: prompt: Text prompt describing the conversation between speakers S1, S2 space_id: HuggingFace Space ID to use """ client = get_client(space_...
Gradio with FastMCP
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
use your Gradio-powered tools to accomplish these tasks.
Gradio with FastMCP
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
The MCP protocol is still in its infancy and you might see issues connecting to an MCP Server that you've built. We generally recommend using the [MCP Inspector Tool](https://github.com/modelcontextprotocol/inspector) to try connecting and debugging your MCP Server. Here are some things that may help: **1. Ensure tha...
Troubleshooting your MCP Servers
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide
= 3 while divisor * divisor <= n_int: while n_int % divisor == 0: factors.append(divisor) n_int //= divisor divisor += 2 if n_int > 1: factors.append(n_int) return factors ``` **3. Ensure that your MCP Client Supports Streamable HTTP** Some MCP Clients do ...
Troubleshooting your MCP Servers
https://gradio.app/guides/building-mcp-server-with-gradio
Mcp - Building Mcp Server With Gradio Guide