Metadata-Version: 2.5
Name: mcp-file-bridge
Version: 0.1.0
Summary: Give external MCP servers a signed, expiring link to user files — no base64, no shared volumes.
Author: liuyurong
License: Apache-2.0
License-File: LICENSE
Keywords: file-transfer,mcp,model-context-protocol,presigned-url
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.10
Provides-Extra: dev
Requires-Dist: langchain-mcp-adapters>=0.1; extra == 'dev'
Requires-Dist: mcp>=1.9; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.110; extra == 'fastapi'
Description-Content-Type: text/markdown

# mcp-file-bridge

**Give an external MCP server a signed, expiring link to a user's file — without base64 and without a shared volume.**

```
/user-uploads/report.pdf   ──►   http://platform/mcp-files/report.pdf?session=…&expires=…&sig=…
                                     ▲
                    the MCP server just does urllib.request.urlopen(...)
```

> Status: v0.1, early. Core + FastAPI endpoint + argument rewriter are usable; the LangChain adapter is next.

---

## The gap this fills

MCP has **no file-upload primitive for tool arguments**. Tool *results* can carry
[resource links and embedded resources](https://modelcontextprotocol.io/specification/2025-06-18/server/tools),
but the client → server direction has nothing. The official
[File Uploads working group](https://modelcontextprotocol.io/community/working-groups/file-uploads/)
puts it plainly: servers "resort to prose instructions asking for base64 strings or local paths".

So everybody improvises. The five patterns you will actually meet:

| Pattern | Works when | Breaks when |
|---|---|---|
| Pass a local path / use `roots` | client and server share a filesystem | the server is remote |
| Base64 inside the tool argument | files are tiny | 10 MB → 13 MB of JSON, straight through the context window |
| **Signed URL (this library)** | both sides can speak HTTP | network is one-way and the server cannot reach you |
| Vendor upload channel (`attach_file` in ChatGPT, File Uploads in Claude) | you are that vendor | you are not |
| Proxy that base64-encodes paths (`mcp-file-proxy`) | you cannot change the server | large files |

`mcp-file-bridge` implements the third one as a library, and keeps the first one for
stdio servers automatically.

---

## Install

```bash
pip install mcp-file-bridge            # core, zero dependencies
pip install "mcp-file-bridge[fastapi]" # + the download endpoint
```

## Three lines

```python
from fastapi import FastAPI
from mcp_file_bridge import FileBridge, HmacSigner
from mcp_file_bridge.endpoints.fastapi import mount_bridge

app = FastAPI()
bridge = FileBridge(
    root_for=lambda session_id: Path("/data/sessions") / session_id,  # your storage, your rules
    signer=HmacSigner(os.environ["FILE_BRIDGE_SECRET"]),
    base_url="http://platform.internal:8000",   # what the *MCP server* can reach
    ttl=1800,
)
mount_bridge(app, bridge)

url = bridge.link(session_id, "uploads/report.pdf")  # hand this to the tool
```

## Rewriting tool arguments

The framework-agnostic core is one pure function — no LangChain, no MCP SDK:

```python
from mcp_file_bridge.interceptors.rewrite import rewrite_local_paths

args, changed = rewrite_local_paths(
    tool_args,
    session_id=run.thread_id,           # from the runtime, never from the model
    bridge=bridge,
    is_local_path=lambda v: v.startswith("/files/"),
    session_prefix="/files/",
)
if changed:
    call = call.override(args=args)
```

### LangChain / `langchain-mcp-adapters`

The adapter ships with the package and imports nothing from LangChain — it only
relies on the interceptor contract (`name` / `args` / `override()` + a handler).

```python
from langchain_mcp_adapters.client import MultiServerMCPClient
from mcp_file_bridge.adapters.langchain import langchain_bridge

client = MultiServerMCPClient(
    servers,
    tool_interceptors=[
        langchain_bridge(
            bridge,
            session_id=lambda: runtime.thread_id,   # resolved per call
            is_local_path=lambda v: v.startswith("/files/"),
            session_prefix="/files/",
        )
    ],
)
```

### Writing your own adapter

An adapter is ~20 lines: hand it the tool name, the arguments and the session id,
and give back rewritten arguments. If your framework exposes any hook around tool
calls — a middleware, a wrapper, a decorator — that is enough:

```python
args, changed = rewrite_local_paths(args, session_id=sid, bridge=bridge, is_local_path=...)
if changed:
    args = args  # call the tool with these instead
```

If it exposes no hook at all (a closed client with only a `url` field), put a
proxy in front of the MCP server instead — that is the fallback, not the main path.


---

## Design notes

- **Scope comes from the runtime, not the model.** The session id is injected by the
  agent runner. A model cannot widen its own access by inventing an id.
- **Local servers get a path, remote servers get a URL.** A stdio MCP already shares
  your filesystem; a URL there is pure overhead. Decide per server, not globally.
- **Fail loudly.** A path that does not resolve is left untouched (or raises), never
  silently replaced with a default file. Silent fallback is how "it worked" pipelines
  end up training on the wrong data.
- **Storage agnostic.** The library only asks for `root_for(session_id) -> Path`.
  S3, a mounted volume, a database blob store — all yours to implement.

## Security model

A link is a bearer credential for one file, for a few minutes:

- HMAC-SHA256 over `session:path:expires`, compared in constant time;
- URLs expire (default 30 min) and are refused after that;
- `resolve()` refuses paths that escape the session root;
- the endpoint is intentionally anonymous — the signature *is* the authentication.

Put it behind HTTPS in production, keep the TTL short, and do not log full URLs.

---

## Demo

```bash
pip install -e ".[fastapi]"
python demo/demo.py
```

It starts the bridge, mints a link for a file in a temp session, then fetches it the
way an MCP server would, and prints status + byte count.

## Roadmap

- [x] LangChain `MultiServerMCPClient` interceptor
- [ ] Official MCP Python SDK wrapper
- [ ] S3 / MinIO presigned backend
- [ ] TypeScript port
- [ ] `auto` mode: path for stdio, URL for streamable HTTP

## Relationship to SEP-2356

The working group's draft adds a declarative "this argument is a file" descriptor.
When it lands, this library does not become obsolete: the descriptor replaces the
*detection* step, and the signed-link *transport* underneath stays the same. That is
deliberate — the mechanism lives at the transport layer, not in your tool schemas.

## License

Apache-2.0.
