Fortran Companion MCP Server
The Fortran Companion MCP Server equips AI models with 26 tools to write, analyze, modernize, and structure modern Fortran code (F2003/F2018/F2023) across four capability areas:
Author & Verify
explain_best_practices– Retrieve a guide to modern Fortran coding standards and design patterns.lint_code/lint_file– Statically analyze code for legacy syntax, implicit typing, missingintentattributes, and bad practices.format_code/format_file– Auto-format usingfprettifywith configurable indentation, line length, and spacing.compile_project– Compile viagfortran/fpmwith strict flags (-Wall -Wextra -std=f2018, etc.).run_tests– Execute test suites viafpm testormake test.validate_syntax/validate_syntax_file– Fast, build-free syntax checks using fparser2 AST.initialize_project– Scaffold new modular Fortran projects withfpmor Makefile layouts.
Modernize & Refactor
modernize_file– Convert F77 idioms (e.g.,.eq.→==,double precision→ parameterized kinds) and injectiso_fortran_env.verify_regression– Compare legacy and modernized binary outputs to confirm no behavior change.convert_common_to_module– TransformCOMMONblocks into encapsulated modules.rename_legacy_identifiers– Safely rename variables to descriptive modern names within file scope.analyze_pure_candidates– Identify procedures suitable forpure/elementalattributes.audit_implicit_interfaces– Flag call sites lacking explicit interfaces across a project.suggest_refactoring/suggest_refactoring_file– Get idiomatic restructuring recommendations.suggest_design_pattern– Retrieve boilerplate for GoF/modern Fortran patterns (OOP, Generics, RAII, Callbacks, Factory, Observer, Strategy, C-Interop, etc.).
Understand a Codebase
project_metrics– Compute modernization scores, legacy construct counts, LOC, and comment density as a "legacy heatmap."dependency_graph– Generate moduleusedependency graphs with fan-in/fan-out metrics, keystone module detection, mutable-global-state flags, and a Mermaid diagram.find_large_units– Detect oversized procedures/modules by LOC, nesting depth, andSELECT CASEarity.
Scaffold & Interoperate
scaffold_unit_test– Generate unit test templates for specific module procedures.scaffold_hpc_grid– Bootstrap HPC grid/stencil templates using Coarrays or OpenMP.generate_c_bindings– Auto-generate a C binding layer usingiso_c_binding.generate_python_interface– Auto-generate Pythonctypes/numpybinding scripts (also auto-generates C bindings).
Allows AI agents to write, format, compile, lint, and structure modern Fortran code (F2003/F2018/F2023) using best practices and industry design patterns.
Generates NumPy-compatible binding wrapper scripts for Fortran modules, enabling high-performance array data interchange.
Generates Python (ctypes/numpy) binding wrapper scripts to enable integration of Fortran modules with Python.
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., "@Fortran Companion MCP Server lint and compile my Fortran project"
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.
Fortran Companion MCP Server
A Model Context Protocol (MCP) server designed to enable AI models to write, format, compile, lint, and structure modern Fortran code (F2003/F2018/F2023) using best practices and industry design patterns.
🌟 Why This Project?
AI models are trained on large volumes of legacy Fortran code (e.g., Fortran 66, 77, 90). When generating Fortran today, they regularly produce "AI Slop":
Implicit variable typing (omitting
implicit none).Non-standard vendor-specific types (like
real*8orinteger*4instead of standardkindparameters).Obsolescent control structures (numbered loops like
do 10 i = 1, Nandgotostatements).Global state blocks (
commonandequivalence) which violate modern scoping rules.Lack of explicit interfaces (omitting module containers and dummy argument
intentattributes).
This MCP server equips AI agents (in Cursor, Claude Desktop, or Antigravity CLI) with tools to statically check, auto-format, compile, and structure Fortran code. This creates a self-correcting feedback loop where the AI compiles and lints its own work, ensuring only high-quality, modern Fortran is delivered.
Related MCP server: MCP Project Standards Server
🔁 How It Works
You don't call these tools yourself — your AI assistant does, automatically. This is a server your AI talks to — not a CLI you run, not a library you import.
Install it once into your MCP-capable AI host (Claude Desktop, Cursor, or Antigravity CLI — see Setup & Connection below).
Work with your AI as you normally would — ask it to write a new module, modernize a legacy routine, or review a file.
Behind the scenes, the AI uses these tools to check its own work — it lints, compiles, and formats what it just wrote, reads the diagnostics, and fixes its own mistakes before showing you the result.
The net effect: you get modern, standards-compliant Fortran instead of "AI Slop," without hand-correcting the model's output.
👥 Who It's For
Engineers pairing with an AI on Fortran who want generated code to follow F2003/F2018 standards out of the box.
Teams modernizing legacy F77/F90 code — convert fixed-format layouts,
commonblocks, and obsolete types into modular, intent-checked modern Fortran, with regression checks to prove behavior didn't change.Anyone auditing or onboarding onto a large codebase — get project-wide modernization metrics, a module dependency graph, and oversized "god-file" hot spots to see what needs attention first.
🛠️ What It Does (Tool Catalog)
The server exposes 26 MCP tools the AI can call, grouped by purpose:
Author & verify
explain_best_practices— the modern-Fortran style guide the agent is told to follow.lint_code/lint_file— static analysis for obsolete types, missingintent, missingimplicit none, fixed-format layout, and deprecated statements.format_code/format_file— clean indentation and formatting viafprettify.compile_project— strictgfortran/fpmcompilation (-Wall -Wextra -Wimplicit-interface -fcheck=all -std=f2018).run_tests— runs the project'sfpm/maketest suite.validate_syntax/validate_syntax_file— fast, build-free syntax check via the fparser2 AST; preprocess-aware for source laced with C-preprocessor macros.initialize_project— scaffolds a modern modular project (fpm or Makefile layout) with intents and test templates.
Modernize & refactor
modernize_file— converts F77 idioms (.eq.→==,double precision→ parameterized kinds, injectsiso_fortran_env) and reformats.verify_regression— runs legacy vs. modernized binaries and compares output + exit status to prove no behavior change.convert_common_to_module— turns globalcommonblocks into module-scoped state.rename_legacy_identifiers— safe, scoped identifier renaming.analyze_pure_candidates— finds procedures that could becomepure.audit_implicit_interfaces— flags call sites that lack explicit interfaces.suggest_refactoring/suggest_refactoring_file— recommends idiomatic restructurings.suggest_design_pattern— serves architectural blueprints and code templates: OOP (classes, inheritance, polymorphism, deferred bindings), Generics (interface overloading), RAII (allocatablecleanup), Callbacks (Strategy via abstract interfaces / procedure pointers), and C-Interop (iso_c_binding).
Understand a codebase
project_metrics— per-file and aggregate modernization scores and legacy-feature counts.dependency_graph— moduleusegraph with fan-in/fan-out, keystone modules, and mutable-global-state detection.find_large_units— oversized procedures/modules ranked by length, nesting, andselect casearity.
Scaffold & interoperate
scaffold_unit_test/scaffold_hpc_grid— unit-test and HPC grid boilerplate.generate_c_bindings/generate_python_interface—iso_c_bindingC bindings and Python (ctypes/numpy) interfaces.
📂 Project Structure
fortran-mcp/
├── pyproject.toml # Python project configuration & dependencies
├── README.md # Project overview & documentation
├── session_handoff.md # Context handoff for AI agents
├── docs/
│ └── FEATURE_IDEAS.md # Prioritized backlog from large-codebase field use
├── src/
│ └── fortran_mcp/
│ ├── __init__.py
│ ├── linter.py # Custom Fortran linter engine
│ ├── design_patterns.md # Design-pattern blueprints served by the server
│ └── server.py # FastMCP tool definitions and entrypoint
├── test/ # Demonstration and verification test suite
│ ├── unformatted_legacy.f90 # Non-compliant Fortran demonstration file
│ ├── modern_compliant.f90 # Formatted, best-practice compliant Fortran file
│ ├── run_benchmarks.py # Regression & benchmark harness (run in CI)
│ ├── illustrate_mcp_tools.py # Python script orchestrating the MCP tool calls
│ └── README.md # Test runner documentation
└── dist/ # Packaged python distributions (tar/wheel)⚙️ Setup & Connection
This server uses the standard Python MCP SDK (fastmcp) and requires Python 3.14+ (or 3.10+ compatible environments) with uv or pip.
1. Add to Antigravity CLI
Add the server configuration to your local Antigravity config file at ~/.gemini/antigravity-cli/mcp_config.json:
{
"mcpServers": {
"fortran-companion": {
"command": "uv",
"args": [
"--directory",
"/path/to/fortran-mcp",
"run",
"fortran-mcp"
]
}
}
}2. Add to Claude Desktop
To use this with Claude Desktop, insert the block below into your claude_desktop_config.json (typically under ~/Library/Application Support/Claude/ on macOS or %APPDATA%/Claude/ on Windows):
{
"mcpServers": {
"fortran-companion": {
"command": "uv",
"args": [
"--directory",
"/path/to/fortran-mcp",
"run",
"fortran-mcp"
]
}
}
}🚀 How to Test
Start a new conversation session with any MCP-capable host (like Claude or Antigravity) in this workspace. Try prompts like:
"Design a modules-based modern Fortran project that integrates a user-defined function using midpoint integration. Make sure you use modern intents, explicit kinds, and test it."
The agent will use the MCP tools to bootstrap the structure, write, lint, format, and compile the code successfully, correcting its errors on the fly.
Available Tools
24 toolsanalyze_pure_candidatesA
Scans procedures in a file and identifies subprograms suitable for 'pure' or 'elemental' attributes. Helps promote parallelization, vectorization, and side-effect-free code design.
Inputs: file_path (required). Returns: result
audit_implicit_interfacesA
Audits the project and lists all subroutine/function calls lacking an explicit interface. Prevents runtime memory crashes and type mismatches.
Inputs: project_path (required). Returns: result
compile_projectA
Compiles the Fortran project. Automatically detects and runs 'fpm build' or 'make' depending on layout.
Inputs: project_path (required), fortran_version. Returns: result
convert_common_to_moduleB
Extracts a legacy COMMON block and generates an encapsulated modern Fortran module. Comments out the legacy COMMON statement and inserts matching module imports.
Inputs: file_path (required), block_name (required), module_name (required). Returns: result
dependency_graphA
Computes module dependency graph and detects modules exposing mutable public state. Scans all Fortran modules in the project, identifies 'use' statements (excluding standard intrinsics), computes fan-in/fan-out metrics, and generates a Mermaid diagram representing the module hierarchy.
Inputs: project_path (required). Returns: result
explain_best_practicesA
Returns a comprehensive guide of modern Fortran coding standards, design patterns, and practices.
Inputs: no named parameters. Returns: result
find_large_unitsA
Detects oversized procedures and modules (complexity / 'god-unit' analysis). Analyzes physical lines, actual code lines, maximum control-flow nesting depth, and SELECT CASE arity across the project. Highly useful for detecting decomposition targets.
Inputs: project_path (required). Returns: result
format_codeB
Auto-formats a string of Fortran code using fprettify to enforce modern indentation and spacing.
Inputs: code (required), indent, line_length, whitespace, +2 more. Returns: result
format_fileA
Auto-formats a local Fortran file in-place using fprettify to enforce modern indentation and spacing.
Inputs: file_path (required), indent, line_length, whitespace, +2 more. Returns: result
generate_c_bindingsB
Auto-generates a standard C binding layer module for a modern Fortran module. Maps Fortran types to C-compatible types using iso_c_binding, and generates bind(c) wrapper interfaces.
Inputs: file_path (required), module_name (required). Returns: result
generate_python_interfaceA
Auto-generates ctypes/numpy binding wrapper scripts for Python integration. Also calls generate_c_bindings first to ensure the C-binding Fortran code is present.
Inputs: file_path (required), module_name (required). Returns: result
initialize_projectA
Initializes a new, modern Fortran project at the specified path. Uses fpm if available, or bootstraps a standard layout with a Makefile.
Inputs: project_path (required), project_name (required), fortran_version. Returns: result
lint_codeA
Statically analyzes a string of Fortran code for legacy syntax, implicit typing, missing intents, and bad practices.
Inputs: code (required). Returns: result
lint_fileA
Statically analyzes a local Fortran source file for legacy syntax, implicit typing, missing intents, and bad practices.
Inputs: file_path (required). Returns: result
modernize_fileC
Performs automated syntax replacements to jumpstart modernizing a legacy Fortran file. Updates obsolete operators, converts legacy types, and formats spacing.
Inputs: file_path (required), output_path. Returns: result
project_metricsA
Computes project-wide quality metrics and generates a 'legacy heatmap'. Scans all Fortran files in the project, aggregates lines of code, comment density, counts legacy constructs (COMMON, EQUIVALENCE, GOTO, etc.), and assigns a modernization score.
Inputs: project_path (required). Returns: result
rename_legacy_identifiersA
Safely renames legacy variables to descriptive modern names across a file scope. Validates scope rules, renames variables in code while preserving comments, and builds using compiler flags to verify correctness.
Inputs: file_path (required), mapping (required). Returns: result
run_testsA
Runs tests for the project. Automatically detects and runs 'fpm test' or 'make test' depending on layout.
Inputs: project_path (required). Returns: result
scaffold_hpc_gridB
Bootstraps a modern HPC template for grid/stencil calculations using Coarrays or OpenMP. Sets up stencil iteration loops and ghost cell exchange wrappers.
Inputs: project_path (required), grid_name (required), dimensions (required). Returns: result
scaffold_unit_testB
Generates unit testing templates for a specific module procedure. Inspects dummy arguments, intents, and shapes, and registers the test target.
Inputs: file_path (required), procedure_name (required), framework. Returns: result
suggest_design_patternA
Provides boilerplate templates and architectural explanations for modern Fortran design patterns mapping to GoF / Refactoring.Guru.
Inputs: pattern_name (required). Returns: result
suggest_refactoringA
Analyzes a block of Fortran code and suggests modern design patterns and refactoring options mapped to Refactoring Guru.
Inputs: code (required), problem_description. Returns: result
suggest_refactoring_fileA
Analyzes a local Fortran file and suggests modern design patterns and refactoring options mapped to Refactoring Guru.
Inputs: file_path (required), problem_description. Returns: result
verify_regressionA
Runs a legacy binary and a modernized binary, comparing their outputs to verify that the refactoring has no regressions.
Inputs: legacy_exe_command (required), modern_exe_command (required). Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 24 tools
Most tools have distinct purposes, but there are overlapping pairs like format_code/format_file, lint_code/lint_file, and suggest_refactoring/suggest_refactoring_file, which differ only by input (code string vs file). However, the descriptions clearly differentiate them, so ambiguity is low.
The majority of tool names follow a verb_noun pattern (e.g., analyze_pure_candidates, compile_project). A few names like dependency_graph and project_metrics are compound nouns, which deviate slightly but are still clear and readable.
With 24 tools, the server covers a broad range of Fortran development tasks (linting, formatting, modernization, testing, HPC, etc.). While slightly on the high side, each tool serves a specific purpose and the set is well-scoped for a comprehensive companion server.
The tool surface covers the main lifecycle: initialization, compilation, testing, linting, formatting, modernization, design patterns, dependency analysis, and metrics. Minor missing functionality like a direct 'run_project' tool or interactive debugging is acceptable given the server's focus on static analysis and scaffolding.
Maintenance
Related MCP Connectors
30+ deterministic dev and delivery tools: linting, metrics, diagrams, model advice, AI-text checks.
Governance copilot for AI-assisted coding. 72 packs, 532 rules, proof bundles.
Lints + auto-fixes how AI coding agents discover any new product. 24 rules, 6 tools, score 0-100.
AI colleagues that keep your standards, your project and their reasoning between sessions
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceEnables AI coding agents to generate standardized code using scaffolding templates, enforce architectural patterns, and validate outputs programmatically. Supports creating projects from boilerplates and adding features to existing codebases while maintaining team conventions.160AGPL 3.0
- AlicenseAqualityDmaintenanceManages project standards, configurations, and API debugging for AI-assisted development, ensuring unified development practices across teams and machines.1330 npm5MIT
- AlicenseAqualityBmaintenanceEnables AI assistants and developers to analyze code for language-specific best practices and idiomatic patterns across programming languages, CI automation, and configuration formats.162MIT
- FlicenseBqualityDmaintenanceEnables AI assistants to work with Chapel code, including compiling, linting, and accessing educational primers.51-