Skip to main content
Glama
README.md
# SamToolkit — Reusable Python Library + MCP server

A small Python library with two read-only file tools, `inspect_python` and `inspect_csv`, plus a thin
[MCP](https://modelcontextprotocol.io) server (stdio) that exposes them.

The architecture is **core library -> thin MCP adapter -> MCP client**.

It is the tool provider for the supervised agent in
[langchain-harness-lab](https://github.com/yige-fei/langchain-harness-lab), which in turn powers the
AI Agent mode of [LocalCodePilot](https://github.com/yige-fei/Local-Code-Pilot). The library and the
server work on their own, without either of those projects.

**Status:** a personal project, v0.1.0, tested on one machine (macOS 14.4, Apple Silicon, Python 3.12.6).
A fresh install from a `git clone` has not been verified (see [Limitations](#known-limitations)).

## Where to put it

On its own, SamToolkit can live anywhere. **When used with langchain-harness-lab** (and so with
LocalCodePilot's AI Agent mode), it must be at this exact path, because the harness hardcodes it:

```
~/MCP-Toolbox/sam-toolkit-mcp/          this repository
~/MCP-Toolbox/sam-toolkit-mcp/.venv/    its own virtual environment (the harness launches server.py with it)
```

For the harness, create `.venv` with the python.org Python 3.12 installer
(`/Library/Frameworks/Python.framework/Versions/3.12/bin/python3.12`). The harness sandbox only allows
programs from that location to run; see the harness README.

## Prerequisites

- Python 3.12+ (typed MCP output schemas rely on 3.12's `typing.TypedDict`)
- Internet access once, to install the one dependency (`mcp>=2,<3`; tested with `mcp` 2.3.0)
- No Docker, Node.js, Ollama or cloud accounts needed for the tests or the MCP smoke test

```bash
git clone https://github.com/yige-fei/sam-toolkit-mcp.git ~/MCP-Toolbox/sam-toolkit-mcp
cd ~/MCP-Toolbox/sam-toolkit-mcp
/Library/Frameworks/Python.framework/Versions/3.12/bin/python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install -e .
python -m unittest discover -s tests -v
python smoke_test.py
```

`pip install -e .` installs the package in editable mode, together with `mcp>=2,<3`. `smoke_test.py`
launches `server.py` through the MCP SDK client. It checks real stdio MCP tool discovery, two tool calls
and the rejection of a `../` traversal attempt.

Result on 2026-11-26: **80 tests OK**, and the smoke test printed
`PASS: real MCP stdio discovery, 2 tool calls, traversal rejection`. The web-search tests mock all HTTP,
so no request is sent.

## Try the library *without* MCP

```bash
python -c 'from sam_toolkit import inspect_python_file; print(inspect_python_file("examples", "demo.py"))'
```

## Run it as an MCP server

For standalone debug, with a host such as MCP Inspector:

```bash
export SAM_TOOLKIT_WORKSPACE="$PWD/examples"
# `python server.py` runs a stdio MCP server and will look idle until a client speaks.
python server.py
```

Press Ctrl+C to exit. MCP clients should launch the server as a subprocess;
no browser URL or port is required. The Python smoke test does this for you.

### Optional MCP Inspector UI

If you already have a recent Node.js and npx installed, you may run:

```bash
export SAM_TOOLKIT_WORKSPACE="$PWD/examples"
npx @modelcontextprotocol/inspector python server.py
```

Open the URL printed by Inspector, select tools, and call:
- `inspect_python` with `{"path":"demo.py"}`
- `inspect_csv` with `{"path":"sales.csv"}`

Newer Inspector versions may require Node.js 22.19+.

## Exposed tools

- `inspect_python`: parse top-level functions/classes using AST without executing source code.
- `inspect_csv`: summarize rows, columns, and missing values of a small CSV.

Both tools accept **relative paths only** within an explicitly selected
`SAM_TOOLKIT_WORKSPACE`. They never write to the workspace. Files are limited
to 1 MB. The path check protects against basic traversal/symlink escapes,
but it is not an operating-system sandbox and should not be treated as a
race-free guarantee against a malicious local actor.

Do not use this starter to give an untrusted host access to secrets or private
repos. When integrating with LocalCodePilot, preserve its current dispatcher,
permission checks, citation validator, and approved workflow boundaries.

## Error handling

Expected problems (a missing file, a path outside the workspace, a Python
syntax error, a malformed CSV, a blank workspace setting, and so on) raise
`SamToolkitError`. Its message names files only by the relative path you passed
in and never includes absolute filesystem paths. A missing file and a symlink
pointing outside the workspace give the same message, so error text cannot be
used to probe for files outside the workspace.

From Python:

```python
from sam_toolkit import SamToolkitError, inspect_python_file

try:
    result = inspect_python_file("examples", "demo.py")
except SamToolkitError as exc:
    print("Could not inspect:", exc)
```

`SamToolkitError` is a subclass of `ValueError`, so older code that catches
`ValueError` keeps working.

Through MCP, `server.py` turns a `SamToolkitError` into a tool error: the client
receives a result with `isError: true` and text such as
`Error executing tool inspect_python: File is missing or outside the workspace: nope.py`.
Any other exception is treated as a bug: the client sees only a generic
`Error executing tool <name>` message, and the full traceback is logged on the
server's stderr.

### Known limitations

- **No operating-system sandbox.** The checks are ordinary Python path checks
  that run in your user account; they are not a container or permission jail.
- **Not race-free.** A file could be swapped between the check and the read.
- **Everything in the workspace is readable.** Any `.py` or `.csv` file inside
  it, including ones that contain secrets, can be returned to the client.
- **Some message text comes from the file itself.** Python syntax errors and
  CSV parsing errors repeat the parser's message, which can quote small parts
  of the file's content.
- **Server logs may contain absolute paths.** Tracebacks for unexpected errors
  are written to the server's stderr; treat those logs as private.
- **Fixed path when used by the harness.** langchain-harness-lab requires
  `~/MCP-Toolbox/sam-toolkit-mcp` and its `.venv` (see "Where to put it").
- **Fresh install not verified.** The steps above have not been re-run on a
  clean machine. What has been verified is that a copy containing only this
  repository's files passes the full test suite and the smoke test, using the
  existing environment.

## Typed results and output schemas

Each library function declares the shape of its result with a **`TypedDict`**:
a standard-library way to describe "a plain `dict` with these keys and these
value types". The results are still ordinary dictionaries.

| Function | Result type | Keys |
|---|---|---|
| `inspect_python_file` | `PythonInspectionResult` | `file`, `functions` (list of `PythonFunctionInfo`: `name`, `line`, `async`), `classes` (list of `PythonClassInfo`: `name`, `line`, `methods`) |
| `summarize_csv` | `CsvSummary` | `file`, `rows`, `columns`, `missing_values` |

```python
from sam_toolkit import CsvSummary, summarize_csv

summary: CsvSummary = summarize_csv("examples", "sales.csv")
print(summary["rows"])  # 3
```

**Output schemas.** When an MCP client lists tools, each tool advertises a
JSON Schema for its result (`outputSchema`). The MCP SDK builds it from the
`TypedDict` return annotations in `server.py`, so clients and LLM hosts can see
exactly which fields come back and their types, instead of "some object".

**The library still works without MCP.** The types use only the standard
`typing` module; importing `sam_toolkit` loads no MCP or pydantic code.

**Type hints are not runtime checks.** Python does not enforce a `TypedDict`
when the function runs; tools such as mypy or pyright check it while you
develop. Validation happens only at the MCP boundary: the server checks each
result against the schema before sending it (a missing or wrong-typed field
becomes a generic tool error), and the official MCP client checks the result
against the advertised schema. Note that a key *not* declared in the type is
silently dropped from the structured result, which is why the tests compare
structured results with the library's own output.

## Web search (opt-in, locked until Phase 3C)

`web_search(query, max_results=5)` searches the web through
[Ollama's hosted Web Search API](https://docs.ollama.com/capabilities/web-search)
and returns `{"query", "provider", "results": [{"title", "url", "snippet"}]}`.
It uses only the Python standard library. **In this version it cannot send any
request**: every call stops with a `SamToolkitError` saying "no request was sent".

### Zero-payment project policy

This is a personal learning project: no subscriptions, payment cards, paid
credits, pay-as-you-go usage, automatic top-ups or paid fallback providers.
If genuinely free usage cannot be established, live search stays disabled.

### Local Ollama vs hosted search

- `ollama run …` on your Mac is **local inference**: it runs on your machine
  and needs no account.
- Web search is a **hosted service** at `ollama.com`. Ollama's docs say it
  needs a free Ollama account and an API key. At the time of writing, its
  documentation and pricing page do **not** state whether web search is free,
  or what its quotas are.

### Why the key alone does nothing

An API key proves *who* you are to Ollama; it says nothing about cost. So the
library requires **four separate gates** before it will open a connection:

| Gate | Default | Purpose |
|---|---|---|
| `LIVE_SEARCH_RELEASED` in `search_tools.py` | `False` | Code lock: stays `False` until Phase 3C is reviewed |
| `SAM_TOOLKIT_ALLOW_LIVE_SEARCH=1` | unset | You opt in to live searches |
| `SAM_TOOLKIT_CONFIRM_FREE_TIER_ONLY=1` | unset | You confirm you checked the account is free-only |
| `OLLAMA_API_KEY` | unset | Credential, read from the environment only |

Separately, the MCP tool only appears when `SAM_TOOLKIT_ENABLE_WEB_SEARCH=1`.
Registering it does **not** enable network access; the four gates still apply.
Missing or invalid settings fail safely before any network activity.

Never put a real key in a Git-tracked file or paste it into a chat. Set it in
your shell or in your MCP host's server `env` block. `.env` files are ignored by
Git.

### What the confirmation flag does not do

`SAM_TOOLKIT_CONFIRM_FREE_TIER_ONLY=1` is **your acknowledgement**, not proof.
No software flag can guarantee zero charges, because billing is controlled by
your Ollama account settings, not by this code. Before Phase 3C, check on
ollama.com yourself that no payment method or pay-as-you-go billing is set up.

The built-in limit (at most 10 search attempts in any rolling 60 seconds, per
process; attempts that fail at the provider still count) only stops runaway
loops. It cannot guarantee zero charges: it limits how many requests
are made, not what they cost; it resets when the process restarts; and it does
not see other programs using the same key. HTTP 402 (payment), 429 (rate
limit or quota) and other failures are reported once and **never retried**.

### Other safeguards

Fixed HTTPS endpoint; redirects refused, and the key is never sent to a
redirect target; 10-second socket timeout; 1 MB response cap; at most 10
results, with titles and snippets trimmed and only `http`/`https` links kept;
the key never appears in errors. Results are **untrusted third-party text**: a
model should not follow instructions found in them.

HTTPS certificates are checked against Python's default trust store, which
honours the `SSL_CERT_FILE` environment variable. If `HTTPS_PROXY` is set,
urllib tunnels through the proxy and the key stays inside the encrypted
connection to `ollama.com`. Anyone who can change your environment (or your
trusted certificates) could still intercept traffic, so treat that environment
as trusted configuration.

### A no-API-fee alternative

If Ollama's hosted search cannot be confirmed as free, a self-hosted
[SearXNG](https://docs.searxng.org/) instance is the fallback. It needs Docker
or a manual install, with JSON output enabled in `settings.yml`. Only the
request-building and response-parsing parts of `search_tools.py` would change;
the `WebSearchResult` contract and the MCP tool would stay the same. Note that
SearXNG sends your queries to upstream search engines from your own IP address.

## Project tree

```
sam-toolkit-mcp/
├── LICENSE               # MIT (this project's source code only)
├── pyproject.toml
├── README.md
├── server.py             # thin MCP wrapper
├── smoke_test.py         # real MCP stdio client -> server test
├── src/sam_toolkit/
│   ├── __init__.py
│   ├── errors.py          # SamToolkitError
│   ├── filesystem.py      # workspace checks
│   ├── code_tools.py      # pure Python library
│   ├── data_tools.py      # pure Python library
│   └── search_tools.py    # opt-in web search (locked until Phase 3C)
├── examples/
│   ├── demo.py
│   └── sales.csv
└── tests/
    ├── test_core.py       # library tests
    ├── test_search.py     # web search tests (all HTTP mocked)
    └── test_server.py     # in-process MCP adapter tests
```

## Implemented and not implemented

Implemented:

- `inspect_python` and `inspect_csv` as a library and as MCP tools
- typed results and output schemas
- error contract
- a `web_search` function that is permanently locked in this version

Not implemented:

- **Live web search.** `LIVE_SEARCH_RELEASED = False`, and the Phase 3C review has not happened.
- Any write or edit tool, other file types, an operating-system sandbox.

How SamToolkit is used elsewhere: langchain-harness-lab launches this repository's unchanged `server.py`
over stdio. It uses its own `.venv` and only `SAM_TOOLKIT_WORKSPACE=examples/`, and allows only
`inspect_python` and `inspect_csv`. The `web_search` tool is not registered there. A human must approve
every call.

## Licence

This project's source code is released under the [MIT Licence](LICENSE). The only dependency, `mcp`, is
installed from PyPI under its own licence and is not copied into this repository. SamToolkit itself uses
no model. The Qwen2.5-Coder model that the harness uses is covered by its own licence, described in
the harness README, and not by this one.