Secil Canary Historian MCP Server
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Secil Canary Historian MCP Server show me the last 24 hours of readings for tag P431"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Secil Canary Historian MCP Server
Model Context Protocol (MCP) server providing seamless access to Canary Historian plant data for LLM-powered applications.
Overview
The Universal Canary MCP Server enables LLM clients (Claude Desktop, Continue, etc.) to interact with Canary Historian industrial data through natural language queries. This server implements the MCP protocol standard, exposing tools that allow engineers and analysts to access real-time and historical plant data without manual API integration.
Project Status: MVP implemented | Secil Cement Maceira site supported | Mortars Supported | Outão site ongoing
Quick links:
API Contracts (local docs and security notes): see "API Contracts (Local Docs)" below.
Related MCP server: opcua-mcp
Features
✅ MCP Protocol Implementation - FastMCP-based server with tool registration
✅ Ping Tool - Connection testing and health check
✅ Environment Configuration - Flexible configuration via environment variables
✅ Local Tag Dictionary - Offline index seeded from Canary exports keeps natural-language tag mapping reliable even when API search misses
✅ Auto Tag Resolution - Short identifiers (for example
P431) transparently resolve to fully-qualified Canary paths across all tools✅ Comprehensive Testing — Unit/integration suites plus automated health checks
✅ Canary API Integration - Coming in Story 1.2
✅ Data Access Tools - Coming in Stories 1.3-1.7
Installation
Two transport modes are supported and both work without administrator rights:
Mode | Transport | When to use | Install entry point |
Local STDIO (default) | STDIO piping between the MCP client and this repo | Individual laptops, air‑gapped testing, fastest iteration | Run |
Remote HTTP/SSE | HTTP server with SSE streaming | Team-shared VM or container deployment | Use the same repo on a server/VM and expose port 6000 (see Remote HTTP deployment). |
STDIO validation checklist
Double-click
Install-Canary-MCP.cmd(or rundeploy_canary_mcp.ps1) and provide the Canary URLs when prompted.After the script finishes, reopen Claude Desktop (or your MCP client) and run the
pingtool. Success message: “pong – Canary MCP Server is running!”If
pingfails, rerun the installer with--verboseor consultdocs/troubleshooting/DEBUG_MCP_SERVER.md.
For hands-on configuration via uv, jump down to Quick setup (uv).
MCP Server Capabilities
The Canary MCP Server exposes a rich set of capabilities for interacting with the Canary Historian. These are categorized into Tools, Prompts (Workflows), and Resources.
Access Control
Access to the MCP server is secured using OAuth 2.0, the industry-standard protocol for authorization. MCP clients must present a valid bearer token to access the server's resources.
Canary API Authentication
Authentication to the underlying Canary API is handled transparently by the server. The CANARY_API_TOKEN environment variable must be set with a valid API token, which the server uses for all communication with the Canary Historian.
Tools
Tools are functions that can be directly executed by an MCP client.
ping()– sanity check that MCP is reachable. Use before a session starts; it never touches Canary.get_asset_catalog()– quick, offline peek at the curated tag catalog. Ideal for metadata-only discovery or when Canary is offline. Responses obey the 1 MB guardrail and truncate with guidance when necessary.search_tags(search_pattern)– live Canary browse when you already know part of the tag name. Avoid wildcards; pair withget_tag_pathfor NL flows.get_tag_metadata(tag_path)– fetch detailed properties (units, eng limits, descriptions) once you know the fully qualified path. Pitfall: requires the exact historian path; useget_tag_pathto resolve aliases first.get_tag_path(description)– NL → historian path workflow. Returnsconfidence,confidence_label, andclarifying_questionso LLMs know when to proceed or ask the user for more context.get_tag_properties(tag_paths)– batched property lookup for multiple paths. Handy when cross-checking units before issuing large read queries.list_namespaces()– discover namespace roots/folders. Use this to confirm a plant’s structure or to seed UI pickers.get_last_known_values(tag_names)– grab the most recent sample for one or more tags. Automatically falls back to configured views if no data exists in the requested window.read_timeseries(tag_names, start_time, end_time)– canonical path for historical data. Accepts ISO timestamps or Canary relative expressions; watch thecontinuationtoken for paging.get_tag_data2(tag_names, start_time, end_time, aggregate_name?, aggregate_interval?, max_size?)– high-capacity sibling toread_timeseriesthat hits Canary’sgetTagData2endpoint. Use it for large windows or server-side aggregates when you want fewer continuation hops (tunemax_size).get_aggregates(),get_asset_types(view?),get_asset_instances(asset_type, view?, path?),get_events_limit10(limit?, …),browse_status(path?, depth?, include_tags?, view?)– metadata helpers for Canary Views assets/events plus namespace inspection. Usebrowse_statusto walk view hierarchies, confirmnextPath, and verifytags/nodespayloads before doing heavier searches.write_test_dataset(dataset, records, original_prompt, role, dry_run=False)– gated write pathway to the Canary SAF API. OnlyTest/MaceiraandTest/Outaodatasets are allowed, and callers must pass a tester role (defaults totester). Usedry_run=Trueto validate payloads before sending and keeprecordsunder theCANARY_MAX_WRITE_RECORDSlimit.get_server_info()– reports Canary capabilities (timezones, aggregates) and MCP settings. Run it after deployments to ensure the environment is wired correctly.get_metrics()/get_metrics_summary()– Prometheus output vs. human-readable summary of request counts, latency, cache stats. Use for health dashboards or quick CLI checks.get_cache_stats(),invalidate_cache(pattern),cleanup_expired_cache()– manage the local metadata cache when debugging stale data.get_health()– consolidated MCP/circuit-breaker status plus cache/metrics snapshots. Wire it into ops monitors for a high-level heartbeat.
Prompts (Workflows)
Prompts are structured, multi-step workflows that guide an LLM or MCP client through a complex process.
tag_lookup_workflow: A guided workflow for translating a natural-language request (e.g., "the main kiln temperature") into a precise Canary tag path. It orchestrates the use ofget_asset_catalog,search_tags, andget_tag_properties, and emits confidence/clarifying-question signals so LLMs know when to double-check with the user.timeseries_query_workflow: A deterministic workflow for safely and efficiently retrieving historical data. It walks through tag resolution, natural-language time parsing, payload assembly, and continuation handling before summarising results back to the user.
See docs/workflows/prompt-workflows.md for the full step-by-step playbooks, including inputs, outputs, and example conversations.
Resources
Resources provide static data or documentation to the MCP client to aid in constructing valid queries.
maceira_tag_catalog: A JSON resource containing the curated list of tags for the Maceira site, including natural-language descriptions and engineering units. This is the primary reference for tag discovery.canary_time_standards: A JSON resource that provides a reference guide for Canary's relative time expressions (e.g., "Now-1d") and the server's default timezone (Europe/Lisbon).Reference docs: See
docs/resources/resource-index.mdfor every on-disk artifact (tag catalog, time standards, Postman exports) plus RAG feasibility notes and size-guardrail reminders.
Metadata-only Tag Discovery
You can resolve tags without touching the live Canary API by combining the local resources:
Call
get_asset_catalog/ readresource://canary/tag-catalogto fetch candidate paths, descriptions, and units.Use
get_local_tag_candidates(fromsrc/canary_mcp/tag_index.py) to score the catalog entries against your keywords.Feed the results into
get_tag_path, which now emitsconfidence,confidence_label, andclarifying_questionfields so LLMs know whether to proceed (confidence ≥ 0.80) or ask for more context.Keep responses under the 1 MB guardrail (
CANARY_MAX_RESPONSE_BYTES, default 1 000 000). If a response is truncated, the payload includes a preview plus guidance to narrow the query.
Expected Workflow for an MCP Client / LLM
To effectively interact with the Canary Historian, MCP clients and LLMs should follow a structured workflow that leverages the server's capabilities. The server provides guided Prompts (Workflows) and static Resources to ensure reliable and efficient data access.
Tag Discovery: To find a specific tag, the client should use the
tag_lookup_workflow. This prompt orchestrates the use of tools likeget_asset_catalogandsearch_tagsalong with themaceira_tag_catalogresource to translate a user's request (e.g., "main kiln temperature") into a fully qualified Canary tag path.Data Retrieval: Once a tag path is identified, the client should use the
timeseries_query_workflow. This prompt ensures that time ranges are correctly specified (referencingcanary_time_standards) and that theread_timeseriestool is called with valid parameters to fetch the historical data.Bilingual keyword searches & domain context: When searching, pair English keywords with Portuguese synonyms, especially for the Portuguese sites (Maceira, Outão, Pataias, Montijo, Rio Maior, and Martingança), and translate the user's natural-language prompt to extract the key tags, variables, and historian locations that matter. Keep in mind the database stores industrial process data (PLCs, temperature sensors, pressure transmitters, etc.) that is normalized, processed, filtered, or aggregated into meaningful metrics and KPIs across intervals such as weekly or monthly; that context guides better engineering, performance, maintenance, quality, and compliance decisions.
By following these workflows, the client can reliably navigate the Canary Historian, resolve ambiguity, and retrieve data efficiently, abstracting away the complexity of the underlying API.
Quick setup (uv)
Fast path to run locally with uv on Windows, macOS, or Linux.
Prerequisites:
Python 3.12 or 3.13 available on PATH (portable Python works on Windows)
uv installed
Steps:
# 1) Install uv (one-time)
# Windows PowerShell
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
# macOS/Linux
curl -fsSL https://astral.sh/uv/install.sh | sh
# 2) Clone and enter repo
git clone <repository-url>
cd BD-Canary-MCP
# 3) Create and activate virtual env + install deps
uv sync --locked --dev
# 4) Configure environment from template
copy .env.example .env # Windows
# or
cp .env.example .env # macOS/Linux
# Then edit .env with your Canary credentials (no secrets committed)
uv run pip install .
# 5) Validate installation
uv run python scripts/validate_installation.py
# 6) Start the MCP server
uv run canary-mcp
# or
uv run python -m canary_mcp.serverNotes:
Configuration is loaded from .env using python-dotenv.
Use uv run pytest to execute tests; uvx ruff/black for lint/format.
For Claude Desktop integration, see the section below.
Architecture
BD-hackaton-2025-10/
├── src/
│ └── canary_mcp/ # Main MCP server package
│ ├── __init__.py # Package initialization
│ └── server.py # MCP server with tool definitions
├── tests/
│ ├── unit/ # Unit tests
│ │ └── test_project_structure.py
│ └── integration/ # Integration tests
│ └── test_mcp_server_startup.py
├── config/ # Configuration files
├── docs/ # Project documentation
├── pyproject.toml # Python project metadata & dependencies
├── .env.example # Environment variable template
└── README.md # This fileComponent Architecture
┌─────────────────────────────────────────┐
│ LLM Client (Claude Desktop, etc.) │
└────────────────┬────────────────────────┘
│ MCP Protocol
↓
┌─────────────────────────────────────────┐
│ Universal Canary MCP Server │
│ ┌───────────────────────────────────┐ │
│ │ FastMCP Server │ │
│ │ - Tool Registration │ │
│ │ - Request Handling │ │
│ └───────────────────────────────────┘ │
│ ┌───────────────────────────────────┐ │
│ │ MCP Tools │ │
│ │ - ping (connection test) │ │
│ │ - [Canary data tools] │ │
│ └───────────────────────────────────┘ │
└─────────────────────────────────────────┘
↓ (Future)
┌─────────────────────────────────────────┐
│ Canary Views Web API │
│ - Authentication │
│ - Historical Data Access │
│ - Real-time Data Streaming │
└─────────────────────────────────────────┘Deployment
Three deployment modes are now supported. Choose the one that fits your workflow and follow the linked guides for the full playbook.
Option | Transport | Best for | Documentation |
Local MCP (STDIO) | STDIO | Developer laptops, single-machine analysis | |
Remote MCP (HTTP SSE) | HTTP + SSE | Shared VM (e.g. | |
Containerised MCP | HTTP + SSE | Docker/Podman, CI/CD, Kubernetes |
Local STDIO Quick Start
uv sync --locked --dev
cp .env.example .env # set CANARY_MCP_TRANSPORT=stdio and credentials
uv run python -m canary_mcp.serverTry This in Your MCP Client
In Claude Desktop (or another MCP client), start a new chat and run these steps:
Load the ISA‑95/UNS guide resource so the model understands plant structure and naming:
read_resource("resource://canary/uns-tag-guide")Ask a natural‑language question that relies on that context. For example:
“Using the UNS guide you just read, identify the correct Canary tag paths for Kiln 6 main burner temperature at Maceira and show a 24‑hour trend ending now with 5‑minute granularity. Return the chosen tag paths and a short rationale for each mapping.”Tip: If the model is unsure, it should call get_asset_catalog or search_tags and ask a clarifying question before proceeding.
Remote HTTP SSE Quick Start
# edit .env on the server
CANARY_MCP_TRANSPORT=http
CANARY_MCP_HOST=0.0.0.0
CANARY_MCP_PORT=6000
# then launch
uv run python -m canary_mcp.serverVerify the listener with:
scripts/check_mcp.sh http http://vmhost8.secil.pt:6000Container Quick Start
docker compose up --build
# or
podman-compose up --buildInject .env via environment variables or bind mount and place the container behind corporate ingress as needed.
Example .env entries (copy from .env.example)
# Transport (stdio keeps everything local)
CANARY_MCP_TRANSPORT=stdio
# Canary endpoints (read & write)
CANARY_SAF_BASE_URL=https://scunscanary.secil.pt/api/v1
CANARY_VIEWS_BASE_URL=https://scunscanary.secil.pt
# Optional: default view scoping for read_timeseries
CANARY_DEFAULT_VIEW=Secil.Portugal.Default
# Asset metadata view for get_asset_types / get_asset_instances
CANARY_ASSET_VIEW=Views/Maceira.Assets
# Token issued in Canary Identity (Tag Security applies)
CANARY_API_TOKEN=00000000-0000-0000-0000-000000000000
# Write tool guardrails
CANARY_WRITER_ENABLED=true
CANARY_TESTER_ROLES=tester,qa
CANARY_WRITE_ALLOWED_DATASETS=Test/Maceira,Test/Outao
# Vector/RAG knobs (optional)
CANARY_ENABLE_VECTOR_SEARCH=false
CANARY_VECTOR_INDEX_PATH=data/vector-index
CANARY_VECTOR_TOP_K=5
CANARY_VECTOR_DIM=512
CANARY_VECTOR_HASH_SEED=0Set CANARY_MCP_TRANSPORT=http plus CANARY_MCP_HOST/CANARY_MCP_PORT when you promote the same build to a remote VM.
Need a token or Tag Security refresher? See API Contracts (Local Docs) for links to the Canary READ/WRITE PDFs inside docs/aux_files/Canary API.
API Contracts (Local Docs)
Location:
docs/aux_files/Canary APIRead (Views) API: “Canary Labs Historian Views Service API Documentation (v25.4)”
Write (Store & Forward) API: “Canary Labs Historian Store and Forward Service API Documentation (v25.3)”
Authentication & Tag Security
Use
apiToken(configured in Canary Identity) for all API calls. Each token maps to a Canary user.If Tag Security is enabled, the Canary user must have read permissions for Views (READ) and write permissions for the target DataSet(s) (WRITE).
For WRITE via SaF, if the service is remote from the Historian, configure the SaF service with an API token as well.
Backwards compatibility: some endpoints accept
accessTokenifapiTokenis not provided;/getUserTokenremains for legacy flows when credentials are linked to an Identity user.
Project policy: WRITE tool is gated to
Test/*datasets only (e.g.,Test/Maceira,Test/Outao). The helpercanary_mcp.write_guard.validate_test_datasetenforces this rule before any payload is sent to Canary.
Example Requests (READ/WRITE)
READ (Views) — getTagData
Endpoint:
POST {VIEWS_BASE}/api/v2/getTagDataBody (example):
{ "apiToken": "<token>", "tags": ["Maceira.Cement.Kiln6.Temperature.Outlet"], "startTime": "2025-10-30T00:00:00Z", "endTime": "2025-10-31T00:00:00Z", "pageSize": 1000 }Response (shape excerpt):
{ "data": [ {"timestamp": "2025-10-30T12:00:00Z", "value": 26.2, "quality": "Good", "tagName": "...Outlet"} ] }
WRITE (Store & Forward) — session and write sample
Session (token creation flow depends on deployment; refer to SaF docs)
Optionally set
autoCreateDatasets": truefor test environments.
Write request (conceptual example, see SaF v25.3 for exact schema):
{ "apiToken": "<token>", "dataSet": "Test/Maceira", "points": [ {"path": "Test/Maceira/MCP.Telemetry.Success", "timestamp": "2025-10-31T12:00:00Z", "value": 1} ] }
Usage
Test with MCP Inspector
Use the MCP Inspector to interactively test the server without a client:
npx @modelcontextprotocol/inspector uv --directory . run canary-mcpThis launches the Inspector UI in your browser and starts the server via uv from the current directory.
Running the MCP Server
# Start the server
uv run canary-mcp
# Or run directly
uv run python -m canary_mcp.serverRunning Tests
# Run all tests
uv run pytest
# Run unit tests only
uv run pytest -m unit -q
# Run integration tests only (using pytest)
uv run pytest -m integration -q
# Run integration tests with a specific environment (as used in CI)
python scripts/run_integration_tests.py --env testCLI Tool Validator
Use the bundled script to exercise the main MCP tools (skipping network-dependent calls when credentials are absent):
python scripts/test_mcp_tools.py \
--sample-tag "Maceira.Cement.Kiln6.Temperature.Outlet" \
--search-pattern "Kiln*Temp"Operational Smoke Scripts
Quick one-off tests for ops/SRE use cases:
Script | Purpose |
| Dumps the Prometheus exposition string. |
| Shows cache hit/miss counts and entry totals. |
| Forces a cache cleanup cycle and prints the summary. |
| Emits the consolidated MCP health payload (circuit breaker, cache, metrics). |
| Fetches recent historian events with optional view/time filters. |
| Retrieves tag samples/aggregates for a user-specified time window. |
| Purges metadata cache entries matching an optional pattern. |
| Dry-run (or execute) writes into |
| Walks namespace hierarchies, returning |
Refer to docs/development/manual-tool-scripts.md for CLI docs and environment requirements for every script in this table.
Writing Test Telemetry (Test/Maceira + Test/Outao)
Build the payload – each record needs a fully qualified tag under the allowed Test dataset, a numeric value, and (optionally) an ISO timestamp. Missing timestamps default to "now" (UTC).
Dry-run first – set
dry_run=trueto validate dataset, role, and payload size before anything touches Canary.Tester-only – the
roleargument must matchCANARY_TESTER_ROLES(defaults totester). Non-matching roles receive a 403 response.Cleanup guidance – use Canary’s
/deleteRangeendpoint or the historian UI to remove test data after experiments. Because writes are confined toTest/*, production datasets remain untouched.
Sample MCP payload:
{
"tool": "write_test_dataset",
"args": {
"dataset": "Test/Maceira",
"records": [
{
"tag": "Test/Maceira/MCP.Audit.Success",
"value": 1,
"timestamp": "2025-11-07T23:00:00Z"
}
],
"original_prompt": "Log that the kiln temperature sanity check succeeded.",
"role": "tester",
"dry_run": true
}
}Flip dry_run to false once the preview looks correct. The response echoes the captured prompt, role, and record details for auditing.
Vector Index / RAG Pipeline (Optional)
Build the JSONL + embeddings
python scripts/build_vector_index.py \ --source "docs/aux_files/Canary Resources/Canary_Path_description_maceira.json" \ --out data/vector-indexProduces
catalog.jsonl,embeddings.npy,records.json, andmeta.json.Uses a deterministic hash-based embedding (configurable via
CANARY_VECTOR_DIM/--dimension) so the index can be rebuilt without external services or GPU dependencies.
Enable semantic search
CANARY_ENABLE_VECTOR_SEARCH=true CANARY_VECTOR_INDEX_PATH=data/vector-index CANARY_VECTOR_TOP_K=5Keep these in
.env. When enabled,get_local_tag_candidatesaugments keyword hits with top semantic matches (still capped by the 1 MB payload guard).Rebuild cadence
Re-run the script whenever the catalog JSON changes.
The resulting
data/vector-index/directory is ignored by Git; archive it separately if you need to share the index.
Semantic suggestions are additive—the inverted index remains the source of truth, and vector matches include
"source": "vector-index"metadata so MCP clients can explain where each candidate originated.
The script prints a human-readable PASS/WARN/FAIL summary and respects the global 1 MB response guardrail.
Testing the Ping Tool
# Python interactive test
from canary_mcp.server import ping
# Call the ping tool function
response = ping.fn()
print(response)
# Output: "pong - Canary MCP Server is running!"Connecting to Claude Desktop
The primary way to use this MCP server is through Claude Desktop. Follow these steps to connect:
1. Locate Claude Desktop Configuration File
The configuration file is located at:
%APPDATA%\Claude\claude_desktop_config.jsonFull path (Windows):
C:\Users\<YourUsername>\AppData\Roaming\Claude\claude_desktop_config.json2. Add MCP Server Configuration
Create or edit the config file with the following content:
{
"mcpServers": {
"canary-mcp-server": {
"command": "uv",
"args": [
"--directory",
"C:\\Github\\BD\\BD-hackaton-2025-10",
"run",
"python",
"-m",
"canary_mcp.server"
],
"env": {
"PYTHONPATH": "C:\\Github\\BD\\BD-hackaton-2025-10\\src"
}
}
}
}Important Notes:
Replace
C:\\Github\\BD\\BD-hackaton-2025-10with your actual project pathUse double backslashes (
\\) in JSON for Windows pathsRequires Claude Desktop version 0.7.0+ (MCP support)
3. Restart Claude Desktop
Close Claude Desktop completely (check system tray) and restart it. The MCP server should now be connected.
4. Verify Connection
In Claude Desktop, you should see:
MCP server indicator showing "Connected" status
"canary-mcp-server" listed in available servers
Available tools in the interface
5. Use the MCP Tools
You can now interact with Canary Historian data using natural language:
"Use the list_namespaces tool to show me available Canary namespaces"
"Use the search_tags tool to find all temperature sensors"
"Use the read_timeseries tool to get data for tag 'Secil.Line1.Temperature'
from yesterday to now"
"Use the get_server_info tool to check the Canary server connection"Available MCP Tools
ping- Test MCP server connectionlist_namespaces- Browse Canary hierarchical structuresearch_tags- Find tags by pattern matchingTip: When using
search_tags, provide the literal identifier (for exampleP431) without appending wildcard characters—the Canary API handles fuzzy matching internally.get_tag_metadata- Get detailed tag informationget_tag_properties- Retrieve raw engineering properties and historian metadata for tagsread_timeseries- Query historical time-series dataget_server_info- Check Canary server health and info
Detailed Setup Guide: See docs/installation/claude-desktop-setup.md
Configuration
Configuration is managed through environment variables. Copy .env.example to .env and customize:
# Required: Canary API Configuration
CANARY_SAF_BASE_URL=https://scunscanary.secil.pt/api/v1
CANARY_VIEWS_BASE_URL=https://scunscanary.secil.pt
CANARY_API_TOKEN=your-token-here
CANARY_TAG_SEARCH_ROOT=Secil.Portugal
CANARY_TAG_SEARCH_FALLBACKS=
CANARY_LAST_VALUE_LOOKBACK_HOURS=24
CANARY_LAST_VALUE_PAGE_SIZE=500
# Optional: Server Configuration
MCP_SERVER_HOST=localhost
MCP_SERVER_PORT=6000
# Optional: Logging
LOG_LEVEL=INFO
# Optional: Performance Settings
CANARY_TIMEOUT=30
CANARY_POOL_SIZE=10
CANARY_RETRY_ATTEMPTS=6Key Configuration Variables:
CANARY_SAF_BASE_URL- Base URL for Canary SAF (Store and Forward) APICANARY_VIEWS_BASE_URL- Base URL for Canary Views APICANARY_API_TOKEN- Authentication token (required, keep secret!)CANARY_TAG_SEARCH_ROOT- Root namespace used when callingbrowseTags(for exampleSecil.Portugal)CANARY_TAG_SEARCH_FALLBACKS- Additional namespace prefixes (comma-separated) to probe when the root scope is emptyCANARY_LAST_VALUE_LOOKBACK_HOURS- Window (hours) used when retrieving last known valuesCANARY_LAST_VALUE_PAGE_SIZE- Maximum samples requested to resolve last valuesLOG_LEVEL- Logging verbosity: DEBUG, INFO, WARNING, ERROR, CRITICALCANARY_TIMEOUT- Request timeout in seconds (default: 30)CANARY_RETRY_ATTEMPTS- Number of retry attempts for failed requests (default: 6)
See .env.example for the complete list of available configuration options including performance tuning, circuit breaker settings, and session management.
Documentation
Comprehensive documentation is available in the docs/ directory:
API Reference
API Documentation (docs/API.md) - Complete reference for all MCP tools:
Core Data Access Tools: search_tags, get_tag_metadata, read_timeseries, list_namespaces, get_server_info
Performance & Monitoring Tools: get_metrics, get_metrics_summary
Cache Management Tools: get_cache_stats, invalidate_cache, cleanup_expired_cache
Error Codes: Authentication, connection, timeout, circuit breaker errors
Best Practices: Caching strategy, performance optimization, query patterns
Example Queries
Example Query Library (docs/examples.md) - 20+ real-world examples covering:
Validation Use Cases: Sensor validation, cross-validation, data quality checks
Troubleshooting Use Cases: Anomaly diagnosis, pattern identification, performance comparison
Optimization Use Cases: Operating setpoint optimization, energy waste detection, stability analysis
Reporting Use Cases: Daily reports, compliance reporting, shift handovers
Integration Examples: Maintenance alerts, predictive maintenance, energy management
Additional Documentation
Deployment Guide - Complete site rollout and deployment procedures
Architecture - System architecture and design decisions
Multi-Site Configuration - Managing multiple Canary sites
Troubleshooting Guide - Common issues and solutions
PRD & Epics - Product requirements and feature planning
Quick Links
"Find all temperature sensors for Kiln 6"
→ See examples.md: Example 1 (Sensor Validation)
"Show me performance from yesterday"
→ See examples.md: Example 6 (Historical Comparison)
"What tools are available?"
→ See API.md: Core Data Access ToolsDevelopment
Project Structure
src/canary_mcp/ - Main application code
tests/ - Test suite (unit and integration)
docs/ - Documentation (PRD, epics, stories)
config/ - Configuration files
Development Workflow
Install hooks once:
pre-commit install(adds Ruff, Black, and isort to every commit per Story 4.7). No TypeScript lives in this repo yet, so ESLint/Prettier will be added when a TS package appears.Before each PR (quick checklist):
pre-commit run --all-filesuv run pytest -m "unit or not integration" -quv run pytest -m integration -q(requiresCANARY_*creds)uv run pytest --cov=canary_mcp --cov-report=term --cov-report=html --cov-report=json:coverage.jsonpython scripts/ci/check_coverage.py coverage.json --baseline-file docs/coverage-baseline.jsonOpen
htmlcov/index.htmlto inspect changed modules.
See docs/development/testing-and-coverage.md for the expanded playbook, CI job matrix, and guidance on updating the coverage baseline.
Adding New MCP Tools
# In src/canary_mcp/server.py
@mcp.tool()
def your_tool_name(parameter: str) -> str:
"""
Tool description for LLM clients.
Args:
parameter: Parameter description
Returns:
str: Return value description
"""
# Implementation
return "result"Project Status
All planned epics are complete. The MCP server now ships with:
Canary authentication, namespace browsing, tag search, metadata, and timeseries tools
Remote deployment playbooks (Windows & Linux) plus container images
Client onboarding guides and health-check automation
Roadmap
✅ Epic 1 - Story 1.1 (Current)
Python 3.13 project with uv
FastMCP SDK integration
Basic server with ping tool
Testing framework (73% coverage)
Project documentation
✅ Epic 1 - Remaining Stories
Story 1.2: Canary API Authentication & Session Management
Story 1.3: list_namespaces Tool & Validation
Story 1.4: search_tags Tool & Validation
Story 1.5: get_tag_metadata Tool & Validation
Story 1.6: read_timeseries Tool & Validation
Story 1.7: get_server_info Tool & Validation
Stories 1.8-1.11: Testing, error handling, installation, dev environment
✅ Epic 2 - Production Hardening
Performance optimization (caching, connection pooling)
Advanced error handling
Multi-site configuration
Comprehensive documentation
✅ Epic 3 - MVP
Epic 3 - Advanced Features (Future)
Testing
Coverage
Generate the latest coverage reports with:
uv run pytest --cov=canary_mcp --cov-report=term --cov-report=html --cov-report=json:coverage.json
python scripts/ci/check_coverage.py coverage.json --baseline-file docs/coverage-baseline.jsonhtmlcov/index.html→ drill into individual files/lines.scripts/ci/check_coverage.pyenforces Story 4.7’s policy (warn if repo coverage <75 %, fail if regression >5 pp vsdocs/coverage-baseline.json).CI/CD tip: run the two commands above and treat the script’s warning output (
[coverage] WARNING: overall coverage 73% ...) as a non-blocking signal; only regressions >5 pp trigger a non-zero exit code.
Note: automated coverage collection may require Python to be available on PATH inside your environment. If the command fails (for example on Windows Subsystem for Linux without Python), install Python 3.12+ or use the project virtual environment (
.venv/Scripts/python.exe -m pytest ...).
Test Categories
Unit Tests (
tests/unit/) - Fast, isolated component testsIntegration Tests (
tests/integration/) - Server startup and tool invocation testsContract Tests (Future) - API contract validation
Contributing
This is a hackathon project developed following the BMM (BMAD Meta-Method) workflow. See docs/ for:
PRD.md- Product Requirements Documentepics.md- Epic and story breakdownstories/- Individual story implementation plans
License
See LICENSE file.
Support
For questions or issues:
API Documentation - Complete tool reference with error codes
Example Query Library - 20+ real-world use cases
Troubleshooting Guide - Common issues and solutions
Review test files for usage examples (
tests/integration/)Canary API docs: https://readapi.canarylabs.com/25.4/
Generated with Claude Code MCP Protocol: https://modelcontextprotocol.io/
Available Tools
25 toolsbrowse_statusC
Inspect namespace nodes using the browseStatus endpoint.
Inputs: path, view, depth, include_tags. Returns: object
cleanup_expired_cacheA
Remove expired entries from cache.
Story 2.2: Cleans up expired cache entries to free storage space. This is done automatically but can be triggered manually.
Returns: dict[str, Any]: Dictionary containing cleanup results with keys: - success: Boolean indicating if operation succeeded - count: Number of expired entries removed
Example:
json { "success": true, "count": 8 }
Inputs: no named parameters. Returns: object
get_aggregatesB
Fetch supported Canary aggregate definitions (wrapper around getAggregates).
Inputs: no named parameters. Returns: object
get_asset_catalogA
Retrieve curated metadata for Secil Maceira sensors, devices, and historian tags.
This tool compiles information from the Canary auxiliary catalog so LLM or MCP clients
can convert natural-language requests into concrete historian paths. Pair this with
the tag_lookup_workflow prompt and the search_tags tool when the user provides only
a partial description.
Args: refresh: When True, reload the auxiliary files from disk (default: False) limit: Maximum number of tag entries to return inline (default: 200) include_examples: When True, include the raw request examples from the source file
Returns:
dict[str, Any]: Keys include
- success: Whether metadata was loaded
- tags: Inline sample of tag entries limited by limit
- examples: Optional example list (present when include_examples=True)
- total_tags: Number of tag entries available in the catalog
- summary: Metadata about the returned sample (site, counts, truncation)
- resource_uri: The canonical MCP resource URI for the catalog
- refreshed: Whether the cache was refreshed this call
- hint: Guidance for follow-up actions
Inputs: limit, refresh, include_examples. Returns: object
get_asset_instancesC
Return asset instances for a given asset type (wrapper for getAssetInstances).
Inputs: asset_type (required), path, view. Returns: object
get_asset_typesC
Return asset types available in the configured Canary view.
Inputs: view. Returns: object
get_cache_statsB
Get cache statistics.
Story 2.2: Returns cache performance statistics including hit rate, size, and entry count.
Returns: dict[str, Any]: Dictionary containing cache statistics with keys: - success: Boolean indicating if operation succeeded - stats: Cache statistics object
Example:
json { "success": true, "stats": { "entry_count": 42, "total_size_mb": 12.5, "max_size_mb": 100, "cache_hits": 150, "cache_misses": 30, "hit_rate_percent": 83.3, "evictions": 5 } }
Inputs: no named parameters. Returns: object
get_eventsB
Retrieve event data from the Canary historian.
Args: start_time: Start time (ISO timestamp or relative expression like "now-1d") end_time: End time (ISO timestamp or relative expression like "now") limit: Maximum number of events to return (default 10) tag_names: Optional list of tag names to filter events
Returns: dict[str, Any]: Dictionary containing event data with keys: - success: Boolean indicating if operation succeeded - events: List of event records - count: Total number of events returned - error: Error message (only on failure)
Inputs: end_time (required), start_time (required), limit, tag_names. Returns: object
get_events_limit10C
Retrieve recent Canary events (wrapper for getEvents with limit 10 default).
Inputs: view, limit, end_time, start_time. Returns: object
get_healthA
Get MCP server health status including circuit breaker state.
Story 2.3: Advanced Error Handling & Retry Logic Exposes circuit breaker state and system health for monitoring.
Returns: dict[str, Any]: Dictionary containing health status with keys: - status: Overall health status ("healthy", "degraded", "unhealthy") - timestamp: Current timestamp - circuit_breakers: Dictionary of circuit breaker states - cache_health: Cache system health information - metrics_summary: Performance metrics summary
Example:
json { "status": "healthy", "timestamp": "2025-11-01T10:00:00", "circuit_breakers": { "canary-api": { "state": "closed", "failure_count": 0, "state_changes": 2 } }, "cache_health": { "operational": true, "entry_count": 42, "hit_rate_percent": 75.5 } }
Inputs: no named parameters. Returns: object
get_last_known_valuesC
Retrieve the most recent sample for one or more tags.
Inputs: tag_names (required), views. Returns: object
get_metricsB
Get performance metrics in Prometheus format.
Story 2.1: Returns collected metrics including request counts, latencies, cache hit/miss rates, and connection pool statistics.
Returns: str: Metrics formatted in Prometheus text exposition format
Example:
# HELP canary_requests_total Total number of requests by tool # TYPE canary_requests_total counter canary_requests_total{tool_name="search_tags",status_code="200"} 42 ...
Inputs: no named parameters. Returns: result
get_metrics_summaryB
Get human-readable summary of performance metrics.
Story 2.1: Returns aggregated metrics including request counts, latency percentiles, and cache statistics for all MCP tools.
Returns: dict[str, Any]: Dictionary containing metric summaries with keys: - total_requests: Total number of requests processed - by_tool: Per-tool statistics (counts, latencies, cache stats) - cache_stats: Overall cache hit/miss counts - active_connections: Current connection pool usage
Example:
json { "total_requests": 156, "by_tool": { "search_tags": { "request_count": 42, "latency": {"median": 1.2, "p95": 3.5, "p99": 5.1}, "cache_hits": 10, "cache_misses": 32 } }, "cache_stats": {"total_hits": 45, "total_misses": 111}, "active_connections": 3 }
Inputs: no named parameters. Returns: object
get_server_infoA
Get Canary server health and capability information.
This tool retrieves server version, status, supported time zones, and aggregation functions from the Canary historian, along with MCP server configuration details.
Returns: dict[str, Any]: Dictionary containing server information with keys: - success: Boolean indicating if operation succeeded - server_info: Dictionary with Canary server details - mcp_info: Dictionary with MCP server details - error: Error message (only on failure)
Raises: Exception: If authentication fails or API request errors occur
Inputs: no named parameters. Returns: object
get_tag_data2B
Retrieve historian data via Canary getTagData2 endpoint with optional aggregates.
Args: tag_names: Single tag or list of tags (same normalization rules as read_timeseries) start_time: ISO timestamp or relative time string end_time: ISO timestamp or relative time string aggregate_name: Optional aggregate (e.g., TimeAverage2) aggregate_interval: Optional interval (e.g., 00:05:00) when aggregate_name is set max_size: Desired response size (# of samples) before Canary paginates (default 1000)
Returns: dict: Structured response including raw data, count, and metadata summary
Inputs: end_time (required), tag_names (required), start_time (required), max_size, +2 more. Returns: object
get_tag_metadataB
Get detailed metadata for a specific tag in Canary.
This tool retrieves comprehensive metadata for a tag including properties, data type, units, description, and configuration details.
Args: tag_path: Full path or name of the tag to retrieve metadata for
Returns: dict[str, Any]: Dictionary containing tag metadata with keys: - metadata: Dictionary of tag properties - success: Boolean indicating if operation succeeded - tag_path: The tag path that was queried
Raises: Exception: If authentication fails or API request errors occur
Inputs: tag_path (required). Returns: object
get_tag_pathA
Resolve a natural-language tag description to the best-matching tag path.
Args: description: Natural-language description of the desired tag max_results: Maximum number of candidate tags to return bypass_cache: If True, skip cached results and fetch fresh data
Returns: dict[str, Any]: Response containing the most likely tag path and candidates
Inputs: description (required), max_results, bypass_cache. Returns: object
get_tag_propertiesB
Fetch raw tag property dictionaries from Canary getTagProperties API.
Args: tag_paths: List of fully qualified tag paths to fetch properties for.
Returns: dict[str, Any]: { "success": bool, "properties": mapping of tag path -> property dict, "count": number of property payloads returned, "requested": original tag_paths, "cached": always False }
Inputs: tag_paths (required). Returns: object
invalidate_cacheA
Invalidate cache entries matching pattern.
Story 2.2: Clears cached data, optionally filtering by pattern. Use this when configuration changes or fresh data is required.
Args: pattern: SQL LIKE pattern for keys (empty string = invalidate all)
Returns: dict[str, Any]: Dictionary containing invalidation results with keys: - success: Boolean indicating if operation succeeded - count: Number of entries invalidated - pattern: The pattern used (if any)
Example:
json { "success": true, "count": 15, "pattern": "search:%" }
Inputs: pattern. Returns: object
list_namespacesA
List available Canary namespaces from the historian.
This tool retrieves the hierarchical organization of industrial process tags by querying the Canary Views API for namespace information.
Returns: dict[str, Any]: Dictionary containing namespace structure with keys: - namespaces: List of namespace paths - count: Total number of namespaces found - success: Boolean indicating if operation succeeded
Raises: Exception: If authentication fails or API request errors occur
Inputs: no named parameters. Returns: object
mcp_statusB
Checks MCP server connectivity and provides a status message named "mcp status".
Returns: str: A detailed success message with server status, time, weather, and project info.
Inputs: no named parameters. Returns: result
pingA
Simple ping tool to test MCP server connectivity.
Returns: str: Success message confirming server is responding
Inputs: no named parameters. Returns: result
read_timeseriesB
Retrieve historical timeseries data for specific tags and time ranges.
This tool retrieves historical process data from the Canary historian for analysis and troubleshooting.
Args: tag_names: Single tag name or list of tag names to retrieve data for. If a JSON-style string array is provided (e.g. '["tag1","tag2"]'), it will be parsed automatically, but callers should prefer passing an actual list. start_time: Start time (ISO timestamp or relative expression like "now-1d") end_time: End time (ISO timestamp or relative expression like "now") page_size: Number of samples per page (default 1000)
Returns: dict[str, Any]: Dictionary containing timeseries data with keys: - data: List of data points with timestamp, value, quality - count: Total number of data points returned - success: Boolean indicating if operation succeeded - tag_names: The tag names that were queried - start_time: The start time used for the query - end_time: The end time used for the query - hint: Guidance for correct usage
Raises: Exception: If authentication fails or API request errors occur
Note: When retrieving data for multiple tags, the MCP issues POST requests to the Canary historian. Avoid multi-tag GET queries to remain compatible with the API.
Inputs: end_time (required), tag_names (required), start_time (required), views, +1 more. Returns: object
search_tagsA
Search for Canary tags by name pattern.
This tool searches for industrial process tags in the Canary historian that match the provided search pattern. Results are cached for performance.
Hint: combine this tool with the tag_lookup_workflow prompt and the
resource://canary/tag-catalog metadata. Start from literal identifiers
(for example "P431") without introducing wildcards—Canary performs its own
fuzzy matching and rewards precise fragments.
Args: search_pattern: Tag name or pattern to search for (supports wildcards) bypass_cache: If True, skip cache and fetch fresh data (default: False) search_path: Optional namespace path to scope the browseTags query. Defaults to the CANARY_TAG_SEARCH_ROOT environment variable when omitted.
Returns: dict[str, Any]: Dictionary containing search results with keys: - tags: List of matching tags with metadata - count: Total number of tags found - success: Boolean indicating if operation succeeded - pattern: The search pattern used - search_path: The path used to scope the search (may be empty) - cached: Boolean indicating if result came from cache
Raises: Exception: If authentication fails or API request errors occur
Inputs: search_pattern (required), search_path, bypass_cache. Returns: object
write_test_datasetA
Write manual entry samples into approved Test/* datasets via Canary SAF.
Args:
dataset: The Test dataset to target (e.g., "Test/Maceira").
records: List of objects with keys tag, value, and optional timestamp/quality.
original_prompt: Natural-language instruction captured for auditing.
role: Caller role; must match one of CANARY_TESTER_ROLES (default: "tester").
dry_run: When True, validate payload but skip the actual Canary API call.
Returns: Dict summarising the write attempt, including recorded prompt and role metadata.
Inputs: role (required), dataset (required), records (required), original_prompt (required), +1 more. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 25 tools
Several tools have overlapping boundaries: read_timeseries and get_tag_data2 both retrieve historical timeseries with optional aggregates, get_events and get_events_limit10 overlap, and get_tag_metadata vs get_tag_properties both expose tag details. Status/health tools (ping, mcp_status, get_health, get_server_info) also blur connectivity, server health, and capability reporting. Distinct core tools exist, but an agent could easily misselect among these pairs.
Most tool names follow a predictable snake_case verb_noun pattern such as search_tags, get_tag_metadata, list_namespaces, and invalidate_cache. Minor deviations include ping and mcp_status, plus numeric suffixes in get_tag_data2 and get_events_limit10. The convention is still readable and mostly consistent.
At 25 tools, the surface is at the heavy end for a historian server and includes redundant wrappers, connection-test tools, and multiple observability/cache tools. The domain is complex enough to justify many operations, but several tools do not clearly earn their place as separate entries. This feels borderline over-scoped rather than well-scoped.
The server covers a strong historian read/analysis lifecycle: tag discovery, metadata, namespaces, historical timeseries, last-known values, aggregates, events, assets, and cache/health monitoring. Write support is intentionally limited to test datasets, and real-time subscriptions or broader production write operations are absent, but these are minor gaps for the apparent purpose.
Maintenance
Related MCP Connectors
Query Allen-Bradley, Siemens and CODESYS V3 PLC projects, live tags and analyses in plain English.
The grounded data layer for any LLM: governed SQL, metrics, lineage and catalog over your data.
Persistent memory, hybrid search and a goal graph for AI agents, over stdio or remote HTTP.
Company and industrial data for AI assistants: datasets, SQL, dashboards, alarms, with approvals.
Related MCP Servers
- AlicenseAqualityFmaintenanceServer for interacting with Honeycomb observability data. This server enables LLMs like Claude to directly analyze and query your Honeycomb datasets.1442MIT
- AlicenseNot gradedqualityBmaintenanceEnables LLMs to read, write, browse, search, and subscribe to live data on OPC-UA industrial automation servers, with caching, discovery index, and support for stdio or HTTP transports.7MIT
- AlicenseNot gradedqualityBmaintenanceExposes a deterministic, centrality-aware GraphRAG retrieval planner as operator tools over stdio or SSE, letting agents index corpora, run seed-steerable multi-hop retrievals, resolve entities, inspect graph neighborhoods, and fetch documents. All responses come back in milliseconds with zero LLM calls in the query path, so the calling agent does the reasoning while the server handles hop-by-hop retrieval.81 PyPI2MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents and LLM clients to securely query and write PI time-series archives, AF asset databases, elements, attributes, and summaries through standard tool calls, with optional off-by-default tools for building and maintaining AF structures and dry-run modifications.Apache 2.0