Files
ai_studio/Docs/MCP.md
2026-11-17 16:39:43 +00:00

143 lines
6.8 KiB
Markdown

# Programming custom MCP servers for AI Studio
## Built-in web toolset
AI Studio registers **Built-In Web** at launch. Its `retrieve_page` and
`web_search` tools make requests on demand, without an MCP subprocess. Choose a tool, review its JSON input and confirm the call.
Page retrieval takes a `url`. Search takes a `query` and defaults to Bing. Configure a SearXNG
search URL in **Toolbox → Web Search** to override the default. You can attach returned sources
to the next chat message.
## Connect an existing server
Open **Toolbox → MCP Servers**. Choose **Use LM Studio Config** to read
`~/.lmstudio/mcp.json`, or **Import mcp.json** to choose another file. Turn on
the switch beside each server you want to use. It connects immediately and
reconnects the next time AI Studio opens. Turn the switch off to disconnect it.
Each server row shows its own status and offers **Retry** after a failed
connection. Multiple servers can stay connected. Use **Tools** on a connected
row to open its tool inspector. The manual connection form is session-only.
A local profile accepts `command`, an `args` array, `env`, and an optional
absolute `cwd`. Each argument stays a separate string. No shell interprets the
config. Named commands resolve against PATH and common macOS binary folders.
For an ordinary `python` or `python3` command with an absolute script path,
AI Studio also checks for a nearby `.venv` unless the profile sets PATH.
Use an explicit virtual-environment executable for reproducibility.
A remote profile takes a Streamable HTTP `url` and optional `headers`.
Use HTTPS for remote hosts. HTTP is supported on loopback. Keep bearer
credentials in your selected file or in the manual session-only field.
Copy examples with placeholders and supply your own values locally.
```json
{
"mcpServers": {
"my-local-knowledge": {
"command": "/absolute/project/.venv/bin/python",
"args": ["-u", "/absolute/project/server.py"],
"cwd": "/absolute/project",
"env": { "PYTHONUNBUFFERED": "1" }
},
"my-remote-tools": {
"url": "https://tools.example.com/mcp",
"headers": { "Authorization": "Bearer YOUR_TOKEN" }
}
}
}
```
The attached archive's `src/knowledge_mcp.py` matches the installed
`local-knowledge` program. Select that profile to discover
`search_knowledge`, which accepts `query` and an optional `limit`. Run a query
in Toolbox, review the returned passages, then attach the result to chat.
The MCP index remains with its server. AI Studio's native **Knowledge Stacks**
can separately index files you import in Workspace.
## Remote Knowledge Stacks
A connected MCP profile that exposes `search_knowledge` appears under
**Workspace → Knowledge Stacks → Remote Stacks** and **Resources → Remote Stacks**
in chat. Select a server by its profile name to send that chat's knowledge
queries to that server. **Automatic** uses the first compatible connection.
**Off** disables remote knowledge retrieval for the chat. This selection is
separate from the local stack picker. **Browse Sources** lists indexed paths
when the server exposes `list_knowledge_sources`. Remote indexes are managed
on their servers.
## Pegasus index management
Open **Settings → Knowledge Base** to view the Pegasus mount, source and chunk
counts, free space, last run, and available progress. **Start Index Refresh**
runs the existing incremental indexer against the mounted document folder.
The job continues on Pegasus after the Settings window closes. It uses the
existing `pegasus` SSH alias and key-based authentication. If indexing is already
running, wait for it to finish before starting another refresh.
General chat questions use automatic web lookup by default when **Web Search
& Page Retrieval** is enabled in **Settings → Toolbox**. Requests about
private or selected workspace material skip automatic search. Explicit web
search remains available. When **Show Debug Output** is on, the chat transcript displays a debug card
with the latest web retrieval, knowledge base, and agent run details. Web
source links on individual replies remain visible with debugging off.
## Implement a server
Use an official MCP SDK. For stdio, communicate in newline-delimited UTF-8
JSON-RPC on stdout and write logs on stderr. Support initialize, the initialized
notification, tools/list and tools/call. Return a JSON Schema object for each
tool's input, validate arguments server-side, and return structured output or
content entries. Paginate discovery with nextCursor if your listing is large.
A small Python example using the Python SDK's FastMCP interface:
```python
from mcp.server.fastmcp import FastMCP
server = FastMCP("Example reference tools")
@server.tool()
def lookup(term: str) -> str:
"""Return a short glossary entry."""
glossary = {"SQLite": "An embedded relational database."}
return glossary.get(term, "No matching entry.")
if __name__ == "__main__":
server.run(transport="stdio")
```
Use your virtual environment's Python and select the executable plus script
in an MCP profile. See the [MCP stdio and HTTP specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports)
and the [LM Studio configuration format](https://lmstudio.ai/docs/app/mcp).
## Invoke and troubleshoot
- Select a discovered tool and inspect **Input Schema**. Enter JSON arguments
and confirm the call. Tool runs are manual. You can attach the resulting JSON
to the next reply in the active chat.
- **Executable unavailable:** set the absolute binary path or check the
profile's PATH. A GUI app may start with a different PATH than Terminal.
- **Configured script does not exist:** correct its path in the source
configuration and choose **Reload**. AI Studio cannot find files moved out
of a previous working directory.
- **Server closes or times out:** inspect the error and captured stderr.
Confirm the virtual environment has the dependencies. Keep startup banners
and logs off stdout. The stdio client waits 30 seconds per request.
- **HTTP 401/403:** check the configured authorization header and token.
Confirm that the URL is the MCP endpoint rather than the service homepage.
- **Discovery works but a tool fails:** compare your JSON with its input
schema and check the server's own logs. The app sends an invocation once.
The HTTP client supports legacy and stateless discovery. The stdio client
supports legacy protocol initialization. OAuth negotiation, server-requested
follow-up inputs, and automatic model-driven dispatch are outside this implementation.
### Existing Gitea profile
The obsolete stdio script can be replaced by a working local GiteaMCP
checkout. If it normally starts in HTTP mode, use its Streamable HTTP URL
profile, or use a Python entry point that starts its MCP object in stdio
mode. Give the server an interpreter with the dependencies it expects.
Reload the configuration in Toolbox when you change it.