Source Code Reference¶
This page contains the complete API reference for Tramlines, automatically generated from the source code.
Core Components¶
CLI Module¶
tramlines.cli
¶
Tramlines CLI Entrypoint.
This module contains the command-line interface for running the Tramlines proxy. It handles argument parsing, configuration loading, and server initialization.
Classes¶
Functions¶
app() -> None
¶
CLI entrypoint for running the Tramlines proxy server.
Source code in src/tramlines/cli.py
Logger¶
tramlines.logger
¶
Middleware¶
tramlines.middleware
¶
Classes¶
SessionManager(max_calls_per_session: int = 30, cleanup_hours: int = 24)
¶
Manages session-based call histories with automatic cleanup.
Source code in src/tramlines/middleware.py
Functions¶
get_session_id() -> str
¶
Get session ID from FastMCP context with fallbacks.
get_history(session_id: str) -> CallHistory
¶
Get or create call history for session.
Source code in src/tramlines/middleware.py
cleanup_stale_sessions() -> None
¶
Remove sessions inactive beyond cleanup interval.
Source code in src/tramlines/middleware.py
stats() -> dict
¶
Get session statistics.
GuardRailMiddleware(policy: Policy | None = None, disabled_tools: list[str] | None = None, **kwargs)
¶
Bases: Middleware
Unified middleware that handles security policies, performance monitoring, and call history tracking in a single clean implementation.
Now with session-based call history management for multi-user support.
Source code in src/tramlines/middleware.py
Functions¶
on_call_tool(context: MiddlewareContext[mt.CallToolRequestParams], call_next) -> mt.CallToolResult
async
¶
Handle tool call with security and tracking.
Source code in src/tramlines/middleware.py
on_list_tools(context: MiddlewareContext[mt.ListToolsRequest], call_next)
async
¶
Filter disabled tools.
Source code in src/tramlines/middleware.py
Functions¶
Proxy¶
tramlines.proxy
¶
Classes¶
Functions¶
create_guarded_proxy(mcp_config: dict[str, Any], policy: Policy | None = None, disabled_tools: list[str] = []) -> FastMCP
¶
Create a FastMCP proxy with unified security middleware.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mcp_config
|
dict[str, Any]
|
MCP server configuration |
required |
policy
|
Policy | None
|
Optional security policy to enforce |
None
|
disabled_tools
|
list[str]
|
List of tools to disable |
[]
|
Returns:
Type | Description |
---|---|
FastMCP
|
FastMCP proxy server with security middleware applied |
Source code in src/tramlines/proxy.py
Session¶
tramlines.session
¶
Classes¶
CallStatus
¶
Bases: Enum
The final status of a tool call after evaluation.
ToolCall(name: str, arguments: dict[str, Any], timestamp: datetime = datetime.now(), status: CallStatus = CallStatus.ALLOW, execution_duration: float | None = None)
dataclass
¶
Tool call data for policy evaluation and history tracking.
Guardrail System¶
DSL Context¶
DSL Evaluator¶
tramlines.guardrail.dsl.evaluator
¶
Classes¶
EvaluationResult(action_type: ActionType, violated_rule: str | None = None, message: str | None = None)
dataclass
¶
Functions¶
load_policy_from_file(policy_file: str) -> Policy
¶
Load a security policy from a Python file.
The policy file should define a module-level variable named 'policy' that contains a Policy instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
policy_file
|
str
|
Path to the Python policy file |
required |
Returns:
Name | Type | Description |
---|---|---|
Policy |
Policy
|
The loaded policy object |
Raises:
Type | Description |
---|---|
FileNotFoundError
|
If the policy file doesn't exist |
ValueError
|
If the policy file doesn't contain a valid policy |
ImportError
|
If the policy file has import errors |
Source code in src/tramlines/guardrail/dsl/evaluator.py
evaluate_call(policy: Policy, history: CallHistory) -> EvaluationResult
¶
Evaluates guardrail rules for a given tool call.
Source code in src/tramlines/guardrail/dsl/evaluator.py
DSL Predicates¶
tramlines.guardrail.dsl.predicates
¶
Classes¶
BasePredicate
¶
ValueBuilder(extractor: Callable[[ToolCall, CallHistory], T | None])
¶
StringValueBuilder(extractor: Callable[[ToolCall, CallHistory], T | None])
¶
Bases: ValueBuilder[str]
Value builder with string-specific methods.
Source code in src/tramlines/guardrail/dsl/predicates.py
ComparisonPredicate(extractor: Callable[[ToolCall, CallHistory], T | None], comparison: Callable[[T, Any], bool], target: Any)
¶
Bases: BasePredicate
, Generic[T]
Predicate for comparing extracted values.
Source code in src/tramlines/guardrail/dsl/predicates.py
HistoryQueryBuilder(pattern: str | Pattern[str])
¶
Simplified history query builder.
Source code in src/tramlines/guardrail/dsl/predicates.py
Functions¶
where(condition: Predicate) -> HistoryQueryBuilder
¶
exists() -> Predicate
¶
count(within: str | None = None) -> ValueBuilder[int]
¶
Count matching calls, optionally within a time window.
Source code in src/tramlines/guardrail/dsl/predicates.py
last() -> HistoricalCallBuilder
¶
HistoryExistsPredicate(pattern: Pattern[str], condition: Predicate | None)
¶
Bases: BasePredicate
Check if historical calls matching a pattern exist.
Source code in src/tramlines/guardrail/dsl/predicates.py
HistoricalCallBuilder(pattern: Pattern[str], condition: Predicate | None, reverse: bool)
¶
A builder that provides access to a specific historical call's properties.
Source code in src/tramlines/guardrail/dsl/predicates.py
CustomPredicate(func: Callable[[ToolCall, CallHistory], bool])
¶
Bases: BasePredicate
A wrapper for a raw Python function to be used as a predicate.
Source code in src/tramlines/guardrail/dsl/predicates.py
Functions¶
custom(func: Callable[[ToolCall, CallHistory], bool]) -> Predicate
¶
Provides a clean escape hatch to use a raw Python function for complex logic that cannot be expressed by the declarative DSL.
The function must have the signature:
my_function(call: ToolCall, history: CallHistory) -> bool
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func
|
Callable[[ToolCall, CallHistory], bool]
|
The Python function to wrap in a predicate. |
required |
Returns:
Type | Description |
---|---|
Predicate
|
A Predicate instance that can be used in a .when() clause. |
Source code in src/tramlines/guardrail/dsl/predicates.py
DSL Rules¶
tramlines.guardrail.dsl.rules
¶
Classes¶
RuleBuilder(name: str)
¶
A builder for creating a Rule object in a fluent, step-by-step manner.
Source code in src/tramlines/guardrail/dsl/rules.py
Functions¶
when(condition: Predicate) -> RuleBuilder
¶
Sets the condition (a Predicate) for this rule to trigger.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
condition
|
Predicate
|
The predicate that defines the logic of the rule. |
required |
Returns:
Type | Description |
---|---|
RuleBuilder
|
The RuleBuilder instance for chaining. |
Source code in src/tramlines/guardrail/dsl/rules.py
block(message: str) -> Rule
¶
Finalizes the rule with a BLOCK action. If the condition is met, the tool call will be blocked.
Source code in src/tramlines/guardrail/dsl/rules.py
allow() -> Rule
¶
Finalizes the rule with an ALLOW action. If the condition is met, evaluation of other rules in the same phase stops.
Source code in src/tramlines/guardrail/dsl/rules.py
Functions¶
rule(name: str) -> RuleBuilder
¶
The entry point for creating a new security rule.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
A descriptive name for the rule, used for logging. |
required |
Returns:
Type | Description |
---|---|
RuleBuilder
|
A RuleBuilder instance to define the rule's condition and action. |
Source code in src/tramlines/guardrail/dsl/rules.py
DSL Testing¶
tramlines.guardrail.dsl.testing
¶
Classes¶
Functions¶
assert_allowed(result: EvaluationResult)
¶
Asserts that a tool call was allowed. Raises an AssertionError with a descriptive message if blocked.
Source code in src/tramlines/guardrail/dsl/testing.py
assert_blocked(result: EvaluationResult, by_rule: str | None = None) -> None
¶
Asserts that a tool call was blocked.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
result
|
EvaluationResult
|
The EvaluationResult from a test run. |
required |
by_rule
|
str | None
|
If provided, also asserts that the block was triggered by the rule with this specific name. |
None
|
Raises:
Type | Description |
---|---|
AssertionError
|
If the call was allowed or blocked by a different rule. |
Source code in src/tramlines/guardrail/dsl/testing.py
simulate_calls(policy_under_test: Policy, calls: list[ToolCall]) -> EvaluationResult
¶
Simulates a sequence of tool calls against a policy and returns the final result.
This function simulates what happens in a real session - each call is evaluated as it arrives, with full knowledge of previous calls. If any call is blocked, that result is returned immediately.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
policy_under_test
|
Policy
|
The policy to test against. |
required |
calls
|
list[ToolCall]
|
List of tool calls to simulate in sequence. |
required |
Returns:
Type | Description |
---|---|
EvaluationResult
|
The final EvaluationResult - either the first blocked call or the last call's result. |
Source code in src/tramlines/guardrail/dsl/testing.py
DSL Types¶
tramlines.guardrail.dsl.types
¶
Classes¶
ActionType
¶
Bases: Enum
The type of action a rule can take.
Predicate
¶
Bases: Protocol
A protocol defining the structure of a predicate. It's a callable that evaluates a condition against a tool call and its history.
Rule(name: str, condition: Predicate, action_type: ActionType, message: str | None = None)
dataclass
¶
A single, immutable security rule. It consists of a name, a condition (predicate), and the action to take.
Policy(name: str, rules: List[Rule] = list(), description: str | None = None)
dataclass
¶
A collection of rules that are evaluated in order.
Extensions¶
Encoding Detector¶
tramlines.guardrail.extensions.encoding_detector
¶
Encoding Detection Extension
Detects potentially encoded or obfuscated content that could be used to bypass security checks.
Functions¶
detect_encoding(text: str) -> bool
¶
Detects suspicious encoding or obfuscation in text.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
String to analyze for encoding patterns |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if encoding detected, False if safe |
Source code in src/tramlines/guardrail/extensions/encoding_detector.py
PII Detector¶
tramlines.guardrail.extensions.pii_detector
¶
PII Detection Extension
Uses Microsoft Presidio for detecting personally identifiable information (PII). Provides comprehensive detection of emails, phone numbers, credit cards, SSNs, and more.
Functions¶
detect_pii(text: str) -> bool
¶
Detects personally identifiable information in text.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
String to analyze for PII |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if PII detected, False if safe |
Source code in src/tramlines/guardrail/extensions/pii_detector.py
Prompt Detector¶
tramlines.guardrail.extensions.prompt_detector
¶
Prompt Injection Detection Extension
Uses LlamaFirewall's PromptGuard for detecting jailbreak attempts and prompt injections.
Functions¶
detect_prompt(text: str) -> bool
¶
Detects prompt injection attacks in text.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
String to analyze for prompt injection |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if prompt injection detected, False if safe |
Source code in src/tramlines/guardrail/extensions/prompt_detector.py
Regex Detector¶
tramlines.guardrail.extensions.regex_detector
¶
Regex Threat Detection Extension
Uses LlamaFirewall's RegexScanner for pattern-based threat detection.
Functions¶
detect_regex(text: str) -> bool
¶
Detect potential regex-based threats in text using LlamaFirewall's RegexScanner.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
text
|
str
|
The text to analyze |
required |
Returns:
Type | Description |
---|---|
bool
|
True if potential threats are detected, False otherwise |