Skip to content

Shared Internals API

The modules the servers share. They are private (their names start with _): documented here for contributors and for reading the source, not as a stable API.

Configuration

doc_processing_std_tools._config

Shared configuration module for doc-processing-std-tools.

Loads and caches environment variable configuration. Provides typed access to all DPTTOOLS_* settings with sensible defaults. The container boundary is the primary security layer; these settings provide defense-in-depth.

BrowserConfig dataclass

Configuration for the browser server (DPTTOOLS_BROWSER_*).

ComputerConfig dataclass

Configuration for the computer server (DPTTOOLS_COMPUTER_*).

ConfigError

Bases: Exception

Raised when a DPTTOOLS_* environment variable is invalid.

The message always names the offending variable so a misconfigured deployment fails fast with an actionable error instead of surfacing a confusing ValueError deep inside an unrelated tool.

EnvVar dataclass

Documentation for one environment variable.

ENV_VARS below is the single source for every variable std-tools reads. scripts/gen_reference.py renders the README configuration section, .env.example and the docs site's configuration page from it, and tests/unit/test_config_docs.py fails when a variable in the code is missing here or a generated file is out of date.

ToolsConfig dataclass

Configuration loaded from DPTTOOLS_* environment variables.

bool_env(name, default)

Read a boolean env var (true/false, 1/0, yes/no, on/off).

browser_enabled()

DPTTOOLS_ENABLE_BROWSER: compose the browser server in the launcher.

clear_config_cache()

Clear the cached configuration. Call this after changing env vars in tests.

computer_enabled()

DPTTOOLS_ENABLE_COMPUTER: compose the computer server in the launcher.

get_browser_config()

Browser configuration, cached per process. Raises ConfigError.

get_computer_config()

Computer-server configuration, cached per process. Raises ConfigError.

get_config()

Load configuration from environment variables with defaults.

This function is cached — it reads env vars once per process. Call clear_config_cache() to force a reload (mainly useful in tests).

validate_config(*, browser=False, computer=False)

Eagerly load + validate config so startup fails fast and cleanly.

Returns the loaded config (also warms the cache). With browser=True the browser server's settings are validated too, and likewise with computer=True. Raises ConfigError with the offending variable named.

Safety Utilities

doc_processing_std_tools._safety

Shared safety utilities for doc-processing-std-tools.

Core responsibilities:

  • Path normalization + NUL-byte rejection (NOT containment — see below)
  • File size limit enforcement
  • Output truncation

Security posture: these tools run only inside a secure, isolated, ephemeral, single-session container. The container is the security boundary. sanitize_path is not path containment and does not attempt to block directory traversal: relative .. navigation and absolute paths are legitimate inside the sandbox and are allowed. The only thing rejected is an embedded NUL byte, because Python's own filesystem calls reject it and a clean error message is friendlier than an opaque ValueError from open.

FileSizeLimitError

Bases: Exception

Raised when a file exceeds the configured size limit.

sanitize_path(path)

Normalize a path string; reject only embedded NUL bytes.

This is not containment. The container is the security boundary; relative .. paths and absolute paths are intentionally allowed so the agent can navigate the sandbox freely. Only a NUL byte is rejected (it cannot appear in a real filesystem path and would otherwise surface as an opaque error deep in an open() call).

Parameters:

Name Type Description Default
path str

Raw path string from tool input.

required

Returns:

Type Description
str

The path string unchanged.

Raises:

Type Description
ValueError

If the path contains an embedded NUL byte.

truncate_output(text, hint=None, *, limit=None)

Truncate text if it exceeds the configured output truncation limit.

Parameters:

Name Type Description Default
text str

The output text to potentially truncate.

required
hint str | None

Optional caller-specific remediation hint appended to the truncation notice. Only tools that actually expose pagination (e.g. offset/limit parameters) should pass a hint telling the agent to use them. When None (the default) the notice states only that output was truncated — many callers have no pagination, so the previous hard-coded "use offset/limit parameters" hint was misleading and is no longer the default.

None
limit int | None

Character limit to apply instead of DPTTOOLS_OUTPUT_TRUNCATION_LIMIT.

None

Returns:

Type Description
str

The original text if within limits, or truncated text with a message.

validate_file_size(path)

Check that a file does not exceed the configured size limit.

Parameters:

Name Type Description Default
path Path

Resolved path to the file.

required

Raises:

Type Description
FileSizeLimitError

If the file exceeds DPTTOOLS_MAX_FILE_SIZE_MB.

FileNotFoundError

If the file does not exist.

Image Sizing

doc_processing_std_tools._images

Shared image sizing for every tool that returns an image to the model.

No provider accepts a 50 MB image: an oversized image fails the provider request (and with it the agent turn). fit_image brings an image within the strictest limits across the providers the toolkit supports — a long edge of DPTTOOLS_IMAGE_MAX_EDGE_PX (1568) and an encoded size of DPTTOOLS_IMAGE_MAX_MB (3 MB, i.e. 70% of Anthropic's 5 MB so base64 still fits) — and reports the scale it applied, so callers that map model coordinates back to real pixels (browser / computer servers) can do so.

Images already within both limits are returned byte-identical. An image that has to be resized is first turned upright according to its EXIF orientation (phone photos store pixels sideways and rely on the tag, which re-encoding drops), and transparency is kept, including a PNG's colour-key transparency (tRNS) on an RGB or greyscale image.

FittedImage dataclass

Result of :func:fit_image.

Attributes:

Name Type Description
data bytes

Encoded image bytes.

format str

Lower-case image format for mcp Image (png, jpeg, or the source format when untouched).

scale float

Factor applied to both dimensions (1.0 when untouched).

width int

Width of data in pixels.

height int

Height of data in pixels.

changed bool

False when data is the original bytes.

ImageFitError

Bases: ValueError

The image cannot be brought within the configured limits.

fit_image(source, *, max_edge=None, max_bytes=None)

Bring an image within the model-safe size limits.

Never upscales and keeps the aspect ratio. An image within both limits comes back unchanged. Otherwise it is resized (Lanczos) so the long edge fits, encoded as PNG when the source is PNG or has transparency and as JPEG (quality 85) otherwise, then — while still over the byte limit — JPEG quality steps 85 → 75 → 65 and the scale shrinks by 0.85 per step. A PNG without transparency that is still too big switches to JPEG; a PNG with transparency only shrinks.

Parameters:

Name Type Description Default
source bytes | Path

Encoded image bytes, or a path to an image file.

required
max_edge int | None

Long-edge limit in pixels; defaults to DPTTOOLS_IMAGE_MAX_EDGE_PX.

None
max_bytes int | None

Encoded-size limit in bytes; defaults to DPTTOOLS_IMAGE_MAX_MB megabytes.

None

Returns:

Name Type Description
A FittedImage

class:FittedImage.

Raises:

Type Description
ImportError

Pillow is not installed.

ImageFitError

The image cannot fit without shrinking below MIN_EDGE_PX on its long edge.

Screen Capture

Used by take_screenshot and the computer server's host backend.

doc_processing_std_tools._display

Screen capture shared by take_screenshot and the computer server's host backend. mss and Pillow are optional, so callers import them lazily and pass them in.

capture_to_png_bytes(sct_img, PILImage)

Convert an mss ScreenShot to PNG bytes via Pillow.

open_mss(mss_module, **kwargs)

An mss capture object: mss.MSS (mss 10.2+, where mss.mss is deprecated) or mss.mss on older releases.

On Linux, mss 10.2's default backend, used from a worker thread (which is where every capture here runs), leaves the X server unable to map new windows. The explicit xgetimage backend does not, so Linux pins it.

primary_monitor_index(monitors)

Index in mss().monitors of the primary monitor.

monitors[0] is all monitors combined. mss 10.2 and later mark the primary monitor (is_primary: Windows' primary display, or the X server's XRandR primary output), and that mark wins. Without one, the monitor whose top-left corner is the origin is chosen. That is always the primary on Windows, but not necessarily on X11, where the primary output can sit anywhere and a server may mark none (Xvfb, for one). The last fallback is monitors[1].

Per-session State

Maps an MCP session to a stable key, for the browser and computer servers.

doc_processing_std_tools._sessions

Map an MCP session to a stable key, for servers that keep per-session state (the browser and computer servers).

FastMCP injects a Context into tools that declare one. Its session identifies the connected client; calls with no request context (in-process call_tool, or the toolkit calling a tool function directly) share one default key.

session_key(ctx)

One key per MCP session; DEFAULT_SESSION without a request.