API Reference¶
Generated from docstrings with mkdocstrings.
Top-level package¶
mcp_for_copilot ¶
mcp-for-copilot — an MCP gateway for GPT-6 Sol and friends.
Two ways to use this package:
As a library — wire the layers yourself::
from mcp_for_copilot import Gateway
gw = Gateway(api_key="sk-...", model="gpt-6-sol")
result = await gw.chat("Explain MCP in one paragraph.")
As a server — run the OpenAI-compatible FastAPI app::
mcp-for-copilot serve --port 8000
Layered architecture (each layer is independently testable):
=================== ==================================================
config Configuration — env-driven, no hardcoded secrets
logging_utils Logging — redacts secrets before they are emitted
provider LLM provider adapter — the only place that calls a model
mcp_client MCP client — stdio / http / sse transports
tool_router Tool router — allowlist + argument validation
approval Approval layer — gates risky tools
orchestrator Orchestrator — wires the layers, caps tool rounds
gateway High-level facade + OpenAI-compatible server
=================== ==================================================
ApprovalDecision
dataclass
¶
The approver's verdict.
ApprovalLayer ¶
Wraps an approver callable and enforces fail-closed behaviour.
Source code in src/mcp_for_copilot/approval.py
request
async
¶
Ask the approver. Denies when no approver is configured.
Source code in src/mcp_for_copilot/approval.py
ApprovalRequest
dataclass
¶
ApprovalRequest(
tool: str,
arguments: dict[str, Any] = dict(),
reason: str = "",
round_index: int = 0,
)
What the orchestrator asks the approver to decide on.
Gateway ¶
Gateway(
*,
settings: Settings | None = None,
provider: LLMProvider | None = None,
approver: Approver | None = None,
connect_mcp: bool = True,
)
Owns the provider + MCP client + orchestrator for one process.
Source code in src/mcp_for_copilot/gateway/facade.py
chat
async
¶
chat(
messages: list[dict[str, Any]],
*,
system: str | None = None,
model_id: str | None = None,
max_rounds: int | None = None,
) -> GatewayResult
Run one chat turn through the full tool loop.
Source code in src/mcp_for_copilot/gateway/facade.py
list_tools
async
¶
Return the allowed tools as OpenAI function schemas.
Source code in src/mcp_for_copilot/gateway/facade.py
start
async
¶
Connect to the MCP server(s), if any are configured.
MCP_SERVERS (a JSON array) takes precedence and yields an
:class:MCPClientManager. When it is unset, the deprecated single
MCP_SERVER_URL fields are used exactly as before, so existing
deployments keep working unchanged.
Source code in src/mcp_for_copilot/gateway/facade.py
status ¶
Non-secret status snapshot, safe to return over HTTP.
Source code in src/mcp_for_copilot/gateway/facade.py
GatewayResult
dataclass
¶
GatewayResult(
content: str = "",
model: str = "",
rounds: int = 0,
used_tools: list[str] = list(),
invocations: list[dict[str, Any]] = list(),
usage: dict[str, Any] = dict(),
error: str = "",
plan: list[dict[str, str]] = list(),
plan_progress: dict[str, int] = dict(),
loop_stopped: bool = False,
)
A chat completion plus the tool audit trail.
LLMMCPOrchestrator ¶
LLMMCPOrchestrator(
*,
provider: LLMProvider | None = None,
client: MCPClient | MCPClientManager | None = None,
router: ToolRouter | None = None,
approval: ApprovalLayer | None = None,
settings: Settings | None = None,
)
Drives the model/tool loop with the three gates in place.
Source code in src/mcp_for_copilot/orchestrator.py
run
async
¶
run(
messages: list[dict[str, Any]],
*,
system: str | None = None,
model_id: str | None = None,
max_rounds: int | None = None,
) -> OrchestratorResult
Run the loop and return the final answer with its audit trail.
Source code in src/mcp_for_copilot/orchestrator.py
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |
LLMProvider ¶
LLMProvider(
*,
provider: str | None = None,
api_key: str | None = None,
base_url: str | None = None,
model_id: str | None = None,
timeout: float | None = None,
transport: AsyncBaseTransport | None = None,
fallback_api_key: str | None = None,
fallback_base_url: str | None = None,
fallback_model_id: str | None = None,
fallback_enabled: bool | None = None,
)
OpenAI-compatible chat-completions adapter.
Only openai is implemented. An unknown LLM_PROVIDER raises rather
than falling back, so a misconfiguration is never masked.
Source code in src/mcp_for_copilot/provider.py
fallback_configured
property
¶
True when the Z.ai backup is usable (enabled + key + model).
complete
async
¶
complete(
messages: list[dict[str, Any]],
*,
tools: list[dict[str, Any]] | None = None,
model_id: str | None = None,
max_tokens: int | None = None,
temperature: float | None = None,
reasoning_effort: str | None = None,
) -> ProviderResponse
Send messages to the provider and return a normalised reply.
tools must already be in OpenAI function-calling format; the
adapter does not transform or extend it.
When the primary provider fails with a transport error, timeout, or 5xx and a Z.ai fallback is configured, the same request is retried once against the fallback endpoint. A 4xx is never retried: it is a request problem, not an outage.
Source code in src/mcp_for_copilot/provider.py
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 | |
describe ¶
Non-secret description of the adapter, safe to return over HTTP.
Source code in src/mcp_for_copilot/provider.py
to_openai_tools
staticmethod
¶
Convert MCP tool descriptors into OpenAI function-calling schemas.
Accepts objects exposing name / description / input_schema
(i.e. :class:mcp_for_copilot.mcp_client.MCPTool).
Source code in src/mcp_for_copilot/provider.py
LLMProviderError ¶
Bases: RuntimeError
Raised for any provider failure. The message is always redacted.
MCPCallResult
dataclass
¶
MCPCallResult(
tool: str,
content: str = "",
is_error: bool = False,
raw: dict[str, Any] = dict(),
)
The outcome of one tools/call.
MCPClient ¶
MCPClient(
*,
url: str,
transport: str = "stdio",
auth_token: str = "",
timeout: float = 60.0,
env: dict[str, str] | None = None,
transport_impl: AsyncBaseTransport | None = None,
)
Async MCP client for stdio, http and sse transports.
Source code in src/mcp_for_copilot/mcp_client.py
call_tool
async
¶
Invoke name with arguments and flatten the content blocks.
Source code in src/mcp_for_copilot/mcp_client.py
connect
async
¶
Open the transport and perform the MCP initialize handshake.
Source code in src/mcp_for_copilot/mcp_client.py
list_tools
async
¶
Return every tool the server advertises.
Source code in src/mcp_for_copilot/mcp_client.py
MCPClientError ¶
Bases: RuntimeError
Raised for any MCP transport or protocol failure.
MCPClientManager ¶
Manager for multiple MCP clients.
Source code in src/mcp_for_copilot/mcp_client.py
call_tool
async
¶
call_tool(
client_name: str,
tool_name: str,
arguments: dict[str, Any] | None = None,
) -> MCPCallResult
Call a tool on a specific client.
Source code in src/mcp_for_copilot/mcp_client.py
close
async
¶
from_settings
classmethod
¶
Create an MCPClientManager from settings.
This reads the MCP servers configuration from settings.mcp_servers_parsed and also handles backward compatibility with the deprecated single server fields.
Source code in src/mcp_for_copilot/mcp_client.py
get_client ¶
Get a client by name. If name is None, return the first client (for backward compatibility).
Source code in src/mcp_for_copilot/mcp_client.py
get_client_for_tool ¶
Get the client that provides the given tool, if any.
Source code in src/mcp_for_copilot/mcp_client.py
list_all_tools
async
¶
List tools from all clients and update the tool-to-client mapping.
Returns a dictionary mapping client name to list of tools. Also updates the internal _tool_to_client mapping.
Source code in src/mcp_for_copilot/mcp_client.py
MCPTool
dataclass
¶
A tool advertised by the MCP server.
OrchestratorResult
dataclass
¶
OrchestratorResult(
content: str = "",
model: str = "",
rounds: int = 0,
invocations: list[ToolInvocation] = list(),
usage: dict[str, Any] = dict(),
error: str = "",
plan: list[PlanStep] = list(),
loop_stopped: bool = False,
)
The final answer plus the audit trail of every tool call.
plan_progress
property
¶
Count of steps per status, for a progress display.
ProviderResponse
dataclass
¶
ProviderResponse(
content: str = "",
tool_calls: list[ToolCall] = list(),
model: str = "",
finish_reason: str = "",
usage: dict[str, Any] = dict(),
)
Normalised provider reply.
RoutedTool
dataclass
¶
RoutedTool(
name: str,
description: str = "",
input_schema: dict[str, Any] = dict(),
risky: bool = False,
)
A tool that passed the allowlist, with its declared schema.
RouterDecision
dataclass
¶
RouterDecision(
allowed: bool,
tool: str,
reason: str = "",
needs_approval: bool = False,
arguments: dict[str, Any] = dict(),
)
The router's verdict for one requested tool call.
Settings ¶
Bases: BaseSettings
Runtime configuration, read from the environment or a .env file.
llm_fallback_configured
property
¶
True when the Z.ai backup is usable (enabled + key + model).
mcp_allowed_tools
property
¶
Parsed allowlist. Empty tuple means 'use the default set'.
mcp_servers_parsed
property
¶
Parsed MCP servers configuration. Returns empty list if not configured or invalid.
describe ¶
Non-secret summary, safe to log or return over HTTP.
Source code in src/mcp_for_copilot/config.py
ToolCall
dataclass
¶
A tool invocation requested by the model.
from_openai
classmethod
¶
Parse one entry of choices[0].message.tool_calls.
Malformed JSON arguments are surfaced as an empty dict plus a marker key so the router can reject the call instead of crashing.
Source code in src/mcp_for_copilot/provider.py
ToolInvocation
dataclass
¶
ToolInvocation(
tool: str,
arguments: dict[str, Any] = dict(),
allowed: bool = False,
approved: bool | None = None,
executed: bool = False,
is_error: bool = False,
result: str = "",
reason: str = "",
)
A record of one tool call and what happened to it.
ToolRouter ¶
ToolRouter(
*,
allowed_tools: tuple[str, ...]
| list[str]
| None = None,
require_approval: bool = True,
)
Allowlist + validation gate in front of the MCP server.
Source code in src/mcp_for_copilot/tool_router.py
available ¶
needs_approval ¶
register ¶
Register an MCP tool descriptor (anything with name).
Returns None and skips the tool when it is a gateway self-loop
(gpt6_* / gateway_*): registering those would let the model
call back into this same orchestrator.
Source code in src/mcp_for_copilot/tool_router.py
route ¶
Decide whether name may run, and whether it needs approval.
Source code in src/mcp_for_copilot/tool_router.py
ToolRouterError ¶
Bases: RuntimeError
Raised when a tool call is rejected.
allow_all_approver ¶
Approve every request. Tests and trusted local runs only.
Source code in src/mcp_for_copilot/approval.py
contains_secret ¶
True when text still contains something the redactor would remove.
Used by the test-suite to assert that no secret reaches a log sink.
Source code in src/mcp_for_copilot/logging_utils.py
deny_all_approver ¶
Deny every request.
get_settings
cached
¶
is_risky_tool ¶
Return True when name looks like a mutating operation.
Fails closed: an empty or unparseable name is treated as risky.
Source code in src/mcp_for_copilot/tool_router.py
redact ¶
Return value as a string with every credential-looking substring removed.
Safe to call on any object; None becomes "".
Source code in src/mcp_for_copilot/logging_utils.py
resolve_model_id ¶
Resolve model_id (or the configured default) to a canonical id.
Raises :class:LLMProviderError for an unknown id so a typo fails loudly
instead of silently hitting the provider with a bad name.
Source code in src/mcp_for_copilot/provider.py
safe_log ¶
Log message after redaction.
%-style args are redacted individually so a secret passed as an
argument cannot slip through the format string. Scalar args keep their
type so %d/%f specifiers still work.
Source code in src/mcp_for_copilot/logging_utils.py
static_approver ¶
static_approver(
*,
allow: tuple[str, ...] | list[str] = (),
deny: tuple[str, ...] | list[str] = (),
) -> Approver
Approve tools in allow, deny tools in deny, deny anything else.
Source code in src/mcp_for_copilot/approval.py
validate_arguments ¶
Validate arguments against a JSON-schema subset.
Returns a list of human-readable problems; an empty list means valid.
Supports type, required, properties, enum and items.
Unknown keywords are ignored rather than rejected, so a richer server
schema still works.
Source code in src/mcp_for_copilot/tool_router.py
Configuration¶
mcp_for_copilot.config ¶
Configuration — env-driven, no hardcoded secrets.
Every value has a safe default so the package imports cleanly with an empty environment. A credential is never given a default: an unset key stays empty and the layer that needs it fails loudly instead of silently using a literal.
Settings ¶
Bases: BaseSettings
Runtime configuration, read from the environment or a .env file.
llm_fallback_configured
property
¶
True when the Z.ai backup is usable (enabled + key + model).
mcp_allowed_tools
property
¶
Parsed allowlist. Empty tuple means 'use the default set'.
mcp_servers_parsed
property
¶
Parsed MCP servers configuration. Returns empty list if not configured or invalid.
describe ¶
Non-secret summary, safe to log or return over HTTP.
Source code in src/mcp_for_copilot/config.py
get_settings
cached
¶
Provider¶
mcp_for_copilot.provider ¶
LLM provider adapter.
The single place in the package that talks to a language model. Every other layer (router, approval, orchestrator) is provider-agnostic and only sees the dataclasses defined here.
Design rules¶
- No hardcoded model id. The model always comes from
settings.llm_model_id. A caller may override it per request, but the default is never a literal inside this module. - No hardcoded credential. The key comes from
settings.llm_api_key. - No secret in an error. Every raised message is passed through
:func:
mcp_for_copilot.logging_utils.redact. - Tools are passed through, never invented. The adapter forwards the tool list it is given; it does not add tools of its own.
LLMProvider ¶
LLMProvider(
*,
provider: str | None = None,
api_key: str | None = None,
base_url: str | None = None,
model_id: str | None = None,
timeout: float | None = None,
transport: AsyncBaseTransport | None = None,
fallback_api_key: str | None = None,
fallback_base_url: str | None = None,
fallback_model_id: str | None = None,
fallback_enabled: bool | None = None,
)
OpenAI-compatible chat-completions adapter.
Only openai is implemented. An unknown LLM_PROVIDER raises rather
than falling back, so a misconfiguration is never masked.
Source code in src/mcp_for_copilot/provider.py
fallback_configured
property
¶
True when the Z.ai backup is usable (enabled + key + model).
complete
async
¶
complete(
messages: list[dict[str, Any]],
*,
tools: list[dict[str, Any]] | None = None,
model_id: str | None = None,
max_tokens: int | None = None,
temperature: float | None = None,
reasoning_effort: str | None = None,
) -> ProviderResponse
Send messages to the provider and return a normalised reply.
tools must already be in OpenAI function-calling format; the
adapter does not transform or extend it.
When the primary provider fails with a transport error, timeout, or 5xx and a Z.ai fallback is configured, the same request is retried once against the fallback endpoint. A 4xx is never retried: it is a request problem, not an outage.
Source code in src/mcp_for_copilot/provider.py
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 | |
describe ¶
Non-secret description of the adapter, safe to return over HTTP.
Source code in src/mcp_for_copilot/provider.py
to_openai_tools
staticmethod
¶
Convert MCP tool descriptors into OpenAI function-calling schemas.
Accepts objects exposing name / description / input_schema
(i.e. :class:mcp_for_copilot.mcp_client.MCPTool).
Source code in src/mcp_for_copilot/provider.py
LLMProviderError ¶
Bases: RuntimeError
Raised for any provider failure. The message is always redacted.
ProviderResponse
dataclass
¶
ProviderResponse(
content: str = "",
tool_calls: list[ToolCall] = list(),
model: str = "",
finish_reason: str = "",
usage: dict[str, Any] = dict(),
)
Normalised provider reply.
ToolCall
dataclass
¶
A tool invocation requested by the model.
from_openai
classmethod
¶
Parse one entry of choices[0].message.tool_calls.
Malformed JSON arguments are surfaced as an empty dict plus a marker key so the router can reject the call instead of crashing.
Source code in src/mcp_for_copilot/provider.py
aliases_for ¶
Every alias that resolves to model_id (sorted).
log_provider_summary ¶
Emit a one-line, secret-free summary of the adapter configuration.
Source code in src/mcp_for_copilot/provider.py
resolve_deepseek_tier ¶
Translate a client-facing tier id to its DeepSeek model + effort.
Returns None when model_id is not a DeepSeek tier, so callers can
fall through to the normal alias resolution.
Source code in src/mcp_for_copilot/provider.py
resolve_model_id ¶
Resolve model_id (or the configured default) to a canonical id.
Raises :class:LLMProviderError for an unknown id so a typo fails loudly
instead of silently hitting the provider with a bad name.
Source code in src/mcp_for_copilot/provider.py
MCP client¶
mcp_for_copilot.mcp_client ¶
MCP client — talks to a Model Context Protocol server.
Supports three transports:
stdio
Spawns a subprocess and speaks newline-delimited JSON-RPC over its
stdin/stdout. This is the transport used by mcp-for-copilot mcp.
http
Streamable HTTP: one POST per JSON-RPC message.
sse
Server-Sent Events: POST to the message endpoint, read the reply stream.
The client is an async context manager::
async with MCPClient(url="python -m my_server", transport="stdio") as client:
tools = await client.list_tools()
result = await client.call_tool("read_file", {"path": "README.md"})
MCPCallResult
dataclass
¶
MCPCallResult(
tool: str,
content: str = "",
is_error: bool = False,
raw: dict[str, Any] = dict(),
)
The outcome of one tools/call.
MCPClient ¶
MCPClient(
*,
url: str,
transport: str = "stdio",
auth_token: str = "",
timeout: float = 60.0,
env: dict[str, str] | None = None,
transport_impl: AsyncBaseTransport | None = None,
)
Async MCP client for stdio, http and sse transports.
Source code in src/mcp_for_copilot/mcp_client.py
call_tool
async
¶
Invoke name with arguments and flatten the content blocks.
Source code in src/mcp_for_copilot/mcp_client.py
connect
async
¶
Open the transport and perform the MCP initialize handshake.
Source code in src/mcp_for_copilot/mcp_client.py
list_tools
async
¶
Return every tool the server advertises.
Source code in src/mcp_for_copilot/mcp_client.py
MCPClientError ¶
Bases: RuntimeError
Raised for any MCP transport or protocol failure.
MCPClientManager ¶
Manager for multiple MCP clients.
Source code in src/mcp_for_copilot/mcp_client.py
call_tool
async
¶
call_tool(
client_name: str,
tool_name: str,
arguments: dict[str, Any] | None = None,
) -> MCPCallResult
Call a tool on a specific client.
Source code in src/mcp_for_copilot/mcp_client.py
close
async
¶
from_settings
classmethod
¶
Create an MCPClientManager from settings.
This reads the MCP servers configuration from settings.mcp_servers_parsed and also handles backward compatibility with the deprecated single server fields.
Source code in src/mcp_for_copilot/mcp_client.py
get_client ¶
Get a client by name. If name is None, return the first client (for backward compatibility).
Source code in src/mcp_for_copilot/mcp_client.py
get_client_for_tool ¶
Get the client that provides the given tool, if any.
Source code in src/mcp_for_copilot/mcp_client.py
list_all_tools
async
¶
List tools from all clients and update the tool-to-client mapping.
Returns a dictionary mapping client name to list of tools. Also updates the internal _tool_to_client mapping.
Source code in src/mcp_for_copilot/mcp_client.py
MCPTool
dataclass
¶
A tool advertised by the MCP server.
default_stdio_command ¶
Command used when MCP_SERVER_URL is unset for the stdio transport.
split_command ¶
Split a stdio command line into argv.
shlex.split(posix=False) keeps the surrounding quotes on Windows, so
"C:\Python\python.exe" -m server would try to execute a file literally
named "C:\Python\python.exe". POSIX mode strips the quotes correctly
for both platforms, but it also eats backslashes, so Windows paths are
handled by a small dedicated scanner instead.
Source code in src/mcp_for_copilot/mcp_client.py
Tool router¶
mcp_for_copilot.tool_router ¶
Tool router — the allowlist and argument-validation gate.
Every tool call the model requests passes through here before it can reach the MCP server. The router answers three questions:
- Is this tool allowed at all? (allowlist)
- Is it risky? (needs an approval decision)
- Are the arguments well-formed? (JSON-schema subset validation)
The router fails closed: an unknown tool is denied, and a tool whose name matches a risky verb is treated as risky even if it is not on the explicit list.
RoutedTool
dataclass
¶
RoutedTool(
name: str,
description: str = "",
input_schema: dict[str, Any] = dict(),
risky: bool = False,
)
A tool that passed the allowlist, with its declared schema.
RouterDecision
dataclass
¶
RouterDecision(
allowed: bool,
tool: str,
reason: str = "",
needs_approval: bool = False,
arguments: dict[str, Any] = dict(),
)
The router's verdict for one requested tool call.
ToolRouter ¶
ToolRouter(
*,
allowed_tools: tuple[str, ...]
| list[str]
| None = None,
require_approval: bool = True,
)
Allowlist + validation gate in front of the MCP server.
Source code in src/mcp_for_copilot/tool_router.py
available ¶
needs_approval ¶
register ¶
Register an MCP tool descriptor (anything with name).
Returns None and skips the tool when it is a gateway self-loop
(gpt6_* / gateway_*): registering those would let the model
call back into this same orchestrator.
Source code in src/mcp_for_copilot/tool_router.py
route ¶
Decide whether name may run, and whether it needs approval.
Source code in src/mcp_for_copilot/tool_router.py
ToolRouterError ¶
Bases: RuntimeError
Raised when a tool call is rejected.
is_risky_tool ¶
Return True when name looks like a mutating operation.
Fails closed: an empty or unparseable name is treated as risky.
Source code in src/mcp_for_copilot/tool_router.py
is_self_loop_tool ¶
True when name is a front-end for this same gateway (never servable).
gateway_chat (the HTTP bridge) and the gpt6_* tools (the bundled
stdio server) both call back into this orchestrator, so serving them to
the model would loop: model -> gateway -> gateway -> model.
Source code in src/mcp_for_copilot/tool_router.py
validate_arguments ¶
Validate arguments against a JSON-schema subset.
Returns a list of human-readable problems; an empty list means valid.
Supports type, required, properties, enum and items.
Unknown keywords are ignored rather than rejected, so a richer server
schema still works.
Source code in src/mcp_for_copilot/tool_router.py
Approval¶
mcp_for_copilot.approval ¶
Approval layer — the human-in-the-loop gate for risky tools.
The orchestrator asks this layer before dispatching any tool the router marked as needing approval. The layer fails closed: if no approver is configured, every request is denied rather than silently allowed.
Three approvers ship with the package:
allow_all_approver
Approves everything. For tests and trusted local runs only.
deny_all_approver
Denies everything. The default when nothing is configured.
static_approver
Approves or denies a fixed set of tool names.
ApprovalDecision
dataclass
¶
The approver's verdict.
ApprovalLayer ¶
Wraps an approver callable and enforces fail-closed behaviour.
Source code in src/mcp_for_copilot/approval.py
request
async
¶
Ask the approver. Denies when no approver is configured.
Source code in src/mcp_for_copilot/approval.py
ApprovalRequest
dataclass
¶
ApprovalRequest(
tool: str,
arguments: dict[str, Any] = dict(),
reason: str = "",
round_index: int = 0,
)
What the orchestrator asks the approver to decide on.
allow_all_approver ¶
Approve every request. Tests and trusted local runs only.
Source code in src/mcp_for_copilot/approval.py
deny_all_approver ¶
Deny every request.
static_approver ¶
static_approver(
*,
allow: tuple[str, ...] | list[str] = (),
deny: tuple[str, ...] | list[str] = (),
) -> Approver
Approve tools in allow, deny tools in deny, deny anything else.
Source code in src/mcp_for_copilot/approval.py
Orchestrator¶
mcp_for_copilot.orchestrator ¶
Orchestrator — the model -> tool -> model loop.
One run() call performs up to settings.mcp_max_tool_rounds rounds. Each
round:
- Ask the model, passing the tool schemas it is allowed to use.
- If the model returns no tool calls, the turn is finished.
- For each requested tool call, run the three gates:
a. Allowlist — :class:
~mcp_for_copilot.tool_router.ToolRouterb. Approval — :class:~mcp_for_copilot.approval.ApprovalLayerc. Dispatch — :class:~mcp_for_copilot.mcp_client.MCPClient - Feed the tool results back to the model and repeat.
A denied or failed tool is reported back to the model as an error result rather than aborting the turn, so the model can recover or explain.
LLMMCPOrchestrator ¶
LLMMCPOrchestrator(
*,
provider: LLMProvider | None = None,
client: MCPClient | MCPClientManager | None = None,
router: ToolRouter | None = None,
approval: ApprovalLayer | None = None,
settings: Settings | None = None,
)
Drives the model/tool loop with the three gates in place.
Source code in src/mcp_for_copilot/orchestrator.py
run
async
¶
run(
messages: list[dict[str, Any]],
*,
system: str | None = None,
model_id: str | None = None,
max_rounds: int | None = None,
) -> OrchestratorResult
Run the loop and return the final answer with its audit trail.
Source code in src/mcp_for_copilot/orchestrator.py
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |
LoopDetector ¶
Count repeated identical tool calls and decide when to warn or stop.
This mirrors the CLI loop detection in Cline (soft threshold 3, hard threshold 5): a soft hit injects a warning so the model can change course, and a hard hit ends the turn instead of letting a stuck model burn every remaining round.
Only identical calls count. A model that calls the same tool with different arguments is making progress, not looping.
Source code in src/mcp_for_copilot/orchestrator.py
record ¶
Record one call and report (warn, stop, count).
warn is True only on the first soft hit for a signature, so the
model is nudged once rather than on every subsequent repeat.
Source code in src/mcp_for_copilot/orchestrator.py
OrchestratorResult
dataclass
¶
OrchestratorResult(
content: str = "",
model: str = "",
rounds: int = 0,
invocations: list[ToolInvocation] = list(),
usage: dict[str, Any] = dict(),
error: str = "",
plan: list[PlanStep] = list(),
loop_stopped: bool = False,
)
The final answer plus the audit trail of every tool call.
plan_progress
property
¶
Count of steps per status, for a progress display.
PlanStep
dataclass
¶
One step of the model's working plan.
The plan is advisory: it is the model's own statement of intent, kept so
the caller can show progress and so the model can be reminded of what it
said it would do. It is never used to gate a tool call -- the three gates
in :meth:LLMMCPOrchestrator._handle_tool_call remain the only authority.
ToolInvocation
dataclass
¶
ToolInvocation(
tool: str,
arguments: dict[str, Any] = dict(),
allowed: bool = False,
approved: bool | None = None,
executed: bool = False,
is_error: bool = False,
result: str = "",
reason: str = "",
)
A record of one tool call and what happened to it.
Gateway facade¶
mcp_for_copilot.gateway.facade ¶
Gateway facade — one object that owns the whole stack.
:class:Gateway wires the provider, the MCP client, the router, the approval
layer and the orchestrator together, and manages the MCP connection lifetime.
Typical use::
async with Gateway() as gateway:
result = await gateway.chat([{"role": "user", "content": "List the files"}])
print(result.content)
Gateway ¶
Gateway(
*,
settings: Settings | None = None,
provider: LLMProvider | None = None,
approver: Approver | None = None,
connect_mcp: bool = True,
)
Owns the provider + MCP client + orchestrator for one process.
Source code in src/mcp_for_copilot/gateway/facade.py
chat
async
¶
chat(
messages: list[dict[str, Any]],
*,
system: str | None = None,
model_id: str | None = None,
max_rounds: int | None = None,
) -> GatewayResult
Run one chat turn through the full tool loop.
Source code in src/mcp_for_copilot/gateway/facade.py
list_tools
async
¶
Return the allowed tools as OpenAI function schemas.
Source code in src/mcp_for_copilot/gateway/facade.py
start
async
¶
Connect to the MCP server(s), if any are configured.
MCP_SERVERS (a JSON array) takes precedence and yields an
:class:MCPClientManager. When it is unset, the deprecated single
MCP_SERVER_URL fields are used exactly as before, so existing
deployments keep working unchanged.
Source code in src/mcp_for_copilot/gateway/facade.py
status ¶
Non-secret status snapshot, safe to return over HTTP.
Source code in src/mcp_for_copilot/gateway/facade.py
GatewayResult
dataclass
¶
GatewayResult(
content: str = "",
model: str = "",
rounds: int = 0,
used_tools: list[str] = list(),
invocations: list[dict[str, Any]] = list(),
usage: dict[str, Any] = dict(),
error: str = "",
plan: list[dict[str, str]] = list(),
plan_progress: dict[str, int] = dict(),
loop_stopped: bool = False,
)
A chat completion plus the tool audit trail.
HTTP application¶
mcp_for_copilot.gateway.app ¶
FastAPI app — an OpenAI-compatible gateway in front of GPT-6 Sol + MCP.
Endpoints¶
GET /health
Liveness probe. Always 200 when the process is up.
GET /v1/models
OpenAI-compatible model list.
POST /v1/chat/completions
OpenAI-compatible chat completions, with optional SSE streaming.
GET /v1/status
Non-secret configuration snapshot.
Authentication¶
When GATEWAY_API_KEY is set, every /v1/* request must carry
Authorization: Bearer <key>. When it is empty the gateway accepts any key,
which is intended for local development only.
create_app ¶
Build the FastAPI app. gateway is injectable for tests.
Source code in src/mcp_for_copilot/gateway/app.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 | |
Debug marathon¶
mcp_for_copilot.debug_marathon ¶
Prioritized, sequential debug runs through the GPT-6 model ladder.
DebugMarathon ¶
Own an in-process FIFO job queue and execute tasks one at a time.
Source code in src/mcp_for_copilot/debug_marathon.py
prioritize_tasks ¶
Validate and stably order tasks by priority, difficulty, and complexity.
Source code in src/mcp_for_copilot/debug_marathon.py
MCP server¶
mcp_for_copilot.gateway.server ¶
stdio MCP server — exposes the gateway itself as MCP tools.
Run it directly::
python -m mcp_for_copilot.gateway.server
or let a client spawn it::
mcp-for-copilot mcp
Tools¶
gpt6_chat
Send a prompt to GPT-6 Sol and return the answer, plus the working plan
the model kept (when plan mode is enabled).
gpt6_models
List the models this gateway knows about.
gpt6_status
Report the non-secret gateway configuration.
gpt6_tools
List the MCP tools the gateway is allowed to call.
gpt6_plan
Return the working plan from the most recent gpt6_chat call.
gpt6_debug_marathon
Queue prioritized debug tasks through GPT-6 Luna, Sol, and Astra.
gpt6_debug_marathon_status
Get a queued debug marathon's progress and results.
copilot_install
Verify (and optionally install) the GitHub Copilot CLI.
hubspot_track
Record a lead through VihokAI's own HubSpot route.
vihokai_deploy
Report on, and optionally push, the VihokAI repository.
build_server ¶
Create the MCP server. gateway is injectable for tests.
Source code in src/mcp_for_copilot/gateway/server.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 | |
main ¶
Logging utilities¶
mcp_for_copilot.logging_utils ¶
Secret-safe logging.
Every log line produced by this package goes through :func:safe_log, which
runs the message through :func:redact first. The redactor is deliberately
aggressive: it removes anything that looks like a credential even when the
caller forgot to mark it as one.
Threat model¶
A tool result or an upstream error body can contain a token that the model echoed back, or a connection string with an embedded password. If that text reaches a log file it is a leak, so redaction happens at the boundary rather than at each call site.
contains_secret ¶
True when text still contains something the redactor would remove.
Used by the test-suite to assert that no secret reaches a log sink.
Source code in src/mcp_for_copilot/logging_utils.py
redact ¶
Return value as a string with every credential-looking substring removed.
Safe to call on any object; None becomes "".
Source code in src/mcp_for_copilot/logging_utils.py
redact_mapping ¶
safe_log ¶
Log message after redaction.
%-style args are redacted individually so a secret passed as an
argument cannot slip through the format string. Scalar args keep their
type so %d/%f specifiers still work.
Source code in src/mcp_for_copilot/logging_utils.py
CLI¶
mcp_for_copilot.cli ¶
Command-line interface for the gateway.
Subcommands¶
serve
Run the FastAPI gateway with uvicorn.
mcp
Run the stdio MCP server.
chat
Send one prompt and print the answer.
marathon
Queue debug tasks and poll the job until it finishes.
models
List the known models.
status
Print the non-secret configuration.
main ¶
Entry point for the mcp-for-copilot console script.