# Server

```python
gradio.Server(···)
```

### Description

Server is the Gradio API engine exposed on a FastAPI application (Server mode). It inherits from FastAPI, so all standard FastAPI methods (.get(), .post(), .add_middleware(), .include_router(), etc.) work directly on this instance.  New methods added on top of FastAPI:     api(): Decorator to register a Gradio API endpoint with queue,         SSE streaming, and concurrency control.     mcp: Namespace with .tool(), .resource(), and .prompt() decorators         to tag functions with MCP metadata.     launch(): Creates an internal Blocks, registers deferred API         endpoints, and starts the server.

### Example Usage

```python
from gradio import Server

app = Server()

@app.api(name="hello")
def hello(name: str) -> str:
    return f"Hello {name}"

@app.get("/")
def root():
    return {"message": "Hello World"}

app.launch()
```

### Initialization

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `debug` | `bool` | `False` | Enable debug mode for detailed error tracebacks. |
| `title` | `str` | `"FastAPI"` | The title of the API, shown in the OpenAPI docs. |
| `summary` | `str \| None` | `None` | A short summary of the API. |
| `description` | `str` | `""` | A longer description of the API. Supports Markdown. |
| `version` | `str` | `"0.1.0"` | The version of the API. |
| `openapi_url` | `str \| None` | `"/openapi.json"` | The URL path for the OpenAPI schema. Set to None to disable. |
| `openapi_tags` | `list[dict[str, Any]] \| None` | `None` | Tags for organizing endpoints in the OpenAPI docs. |
| `servers` | `list[dict[str, Any]] \| None` | `None` | Server URLs for the OpenAPI schema. |
| `dependencies` | `Any` | `None` | Global dependencies applied to all routes. |
| `default_response_class` | `Any` | `None` | The default response class for routes. |
| `redirect_slashes` | `bool` | `True` | Whether to redirect trailing slashes. |
| `docs_url` | `str \| None` | `"/docs"` | The URL path for the Swagger UI docs. Set to None to disable. |
| `redoc_url` | `str \| None` | `"/redoc"` | The URL path for the ReDoc docs. Set to None to disable. |
| `middleware` | `Any` | `None` | List of middleware to add to the server. |
| `exception_handlers` | `Any` | `None` | Custom exception handlers. |
| `on_startup` | `Any` | `None` | List of startup event handlers. Prefer lifespan instead. |
| `on_shutdown` | `Any` | `None` | List of shutdown event handlers. Prefer lifespan instead. |
| `lifespan` | `Any` | `None` | An async context manager for startup/shutdown lifecycle. |
| `terms_of_service` | `str \| None` | `None` | URL to the terms of service. |
| `contact` | `dict[str, Any] \| None` | `None` | Contact information dict for the API. |
| `license_info` | `dict[str, Any] \| None` | `None` | License information dict for the API. |
| `root_path` | `str` | `""` | A path prefix for the app when behind a proxy. |
| `root_path_in_servers` | `bool` | `True` | Whether to include root_path in the OpenAPI servers field. |
| `responses` | `dict[int \| str, dict[str, Any]] \| None` | `None` | Additional responses for the OpenAPI schema. |
| `callbacks` | `Any` | `None` | OpenAPI callback definitions. |
| `webhooks` | `Any` | `None` | OpenAPI webhook definitions. |
| `deprecated` | `bool \| None` | `None` | Mark all routes as deprecated. |
| `include_in_schema` | `bool` | `True` | Whether to include all routes in the OpenAPI schema. |
| `generate_unique_id_function` | `Any` | `None` | Custom function to generate unique operation IDs. |
| `separate_input_output_schemas` | `bool` | `True` | Whether to generate separate input/output schemas. |
| `extra` | `Any` | `` |  |
### Demos

**server_app**

[See demo on Hugging Face Spaces](https://huggingface.co/spaces/gradio/server_app)

```python
from gradio import Server
from fastapi.responses import HTMLResponse

app = Server()

@app.mcp.tool(name="add")
@app.api(name="add")
def add(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

@app.mcp.tool(name="multiply")
@app.api(name="multiply")
def multiply(a: int, b: int) -> int:
    """Multiply two numbers together."""
    return a * b

@app.get("/", response_class=HTMLResponse)
async def homepage():
    return """
<!DOCTYPE html>
<html>
<head><title>Calculator</title>
<style>
  * { margin: 0; box-sizing: border-box; font-family: 'Courier New', monospace; }
  body { min-height: 100vh; display: flex; align-items: center; justify-content: center; background: #1a1a2e; color: #fff;}
  .calc { background: #16213e; padding: 2rem; border-radius: 1rem; box-shadow: 0 8px 32px rgba(0,0,0,.4); width: 320px; }
  #out { background: #0f3460; color: #0f0; font-size: 2rem; text-align: right; padding: .75rem 1rem; border-radius: .5rem; min-height: 3rem; margin-bottom: 1rem; }
  .row { display: flex; gap: .5rem; margin-bottom: .5rem; }
  input { flex: 1; min-width: 0; padding: .6rem; font-size: 1.2rem; border: none; border-radius: .5rem; background: #e2e2e2; text-align: center; }
  button { flex: 1; padding: .6rem; font-size: 1rem; border: none; border-radius: .5rem; cursor: pointer; font-weight: bold; color: #fff; }
  .add { background: #e94560; } .mul { background: #533483; }
  button:hover { opacity: .85; }
</style></head>
<body>
  <div class="calc">
    <div id="out">0</div>
    Operands
    <div class="row"><input id="a" type="number" value="3"><input id="b" type="number" value="5"></div>
    Operation
    <div class="row"><button class="add" onclick="run('add')">+</button><button class="mul" onclick="run('multiply')">&times;</button></div>
  </div>
  <script type="module">
    import { client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
    const app = await client(location.origin);
    window.run = async (ep) => {
      const a = parseInt(document.getElementById("a").value), b = parseInt(document.getElementById("b").value);
      document.getElementById("out").textContent = (await app.predict("/" + ep, { a, b })).data;
    };
  </script>
</body>
</html>"""

if __name__ == "__main__":
    app.launch(mcp_server=True)
```

### Methods

#### Description

Event listeners allow you to respond to user interactions with the UI components you've defined in a Gradio Blocks app. When a user interacts with an element, such as changing a slider value or uploading an image, a function is called.

#### Supported Event Listeners

The `Server` component supports the following event listeners:

- `Server.api(fn, ...)`: Decorator to register a function as a Gradio API endpoint. <br> Goes through Gradio's queue with concurrency control and SSE streaming.
- `Server.launch(fn, ...)`: Launch the Gradio API server (Server mode). <br> Parameters match ``Blocks.launch()``; see that method for full descriptions. <br>

#### Event Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `fn` | `Callable \| None` | `None` |  |
| `name` | `str \| None` | `None` |  |
| `description` | `str \| None` | `None` |  |
| `concurrency_limit` | `int \| None \| Literal['default']` | `"default"` |  |
| `concurrency_id` | `str \| None` | `None` |  |
| `queue` | `bool` | `True` |  |
| `batch` | `bool` | `False` |  |
| `max_batch_size` | `int` | `4` |  |
| `api_visibility` | `Literal['public', 'private', 'undocumented']` | `"public"` |  |
| `time_limit` | `int \| None` | `None` |  |
| `stream_every` | `float` | `0.5` |  |
- [Server Mode](https://www.gradio.app/guides/server-mode/)
