Leveraging Gemini CLI and the underlying Gemini LLM to build Model Context Protocol (MCP) AI applications in Fortran deployed to Google Cloud Run.
Why not just use Python?
Python has traditionally been the main coding language for ML and AI tools. One of the strengths of the MCP protocol is that the actual implementation details are independent of the development language. The reality is that not every project is coded in Python- and MCP allows you to use the latest AI approaches with other coding languages.
Fortran? Should I maybe bring an Abacus too?
The goal of this article is to provide a minimal viable basic working MCP stdio server in Fortran that can be run locally without any unneeded extra code or extensions.
So how does this thaumaturgy work?
It is theoretically possible to implement the stack needed with only valid Fortran language constructs. The key to this solution is that modern compiled Fortran supports importing bindings from C during the compilation process.
A fully functional C MCP library is here:
GitHub - micl2e2/mcpc: Cross-platform C SDK for Model Context Protocol (MCP), in modern🚀 C23.
What Is Fortran?
Fortran (FORmula TRANslation) is a high-level, compiled programming language, the first of its kind, created by IBM in the 1950s for scientific and engineering applications, known for its exceptional performance in numerical, computational, and high-performance computing (HPC) tasks like weather modeling, fluid dynamics, and physics simulations, with modern versions supporting parallel processing and object-oriented features while remaining relevant due to its speed and specialized libraries.
The main Fortran site is here:
The Fortran Programming Language - Fortran Programming Language
Installing Fortran
The step by step instructions vary by platform- for a basic Debian system here are the steps:
sudo apt update
sudo apt install build-essential
sudo apt install gcc
sudo apt install gfortran
gfortran --version
xbill@penguin:~/gemini-cli-codeassist/mcp-https-fortran$ gfortran --version
GNU Fortran (Debian 12.2.0-14+deb12u1) 12.2.0
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Gemini CLI
If not pre-installed you can download the Gemini CLI to interact with the source files and provide real-time assistance:
npm install -g @google/gemini-cli
Testing the Gemini CLI Environment
Once you have all the tools and the correct Node.js version in place- you can test the startup of Gemini CLI. You will need to authenticate with a Key or your Google Account:
gemini
Node Version Management
Gemini CLI needs a consistent, up to date version of Node. The nvm command can be used to get a standard Node environment:
C MCP Documentation
The official MCP C page provides samples and documentation for getting started:
GitHub - micl2e2/mcpc: Cross-platform C SDK for Model Context Protocol (MCP), in modern🚀 C23.
This C library is built and the low level bindings can be used from Fortran code.
Where do I start?
The strategy for starting MCP development is a incremental step by step approach.
First, the basic development environment is setup with the required system variables, and a working Gemini CLI configuration.
Then, a minimal Hello World Style Fortran MCP Server is built with HTTP transport using the C library bindings. This server is validated with Gemini CLI in the local environment.
This setup validates the connection from Gemini CLI to the local process via MCP. The MCP client (Gemini CLI) and the MCP server both run in the same local environment.
Next- the basic MCP server is wrapped in a container and deployed to Google Cloud Run. This remote endpoints is validated with the local copy of Gemini CLI.
Setup the Basic Environment
At this point you should have a working Fortran and C environment and a working Gemini CLI installation. The next step is to clone the GitHub samples repository with support scripts:
cd ~
git clone https://github.com/xbill9/gemini-cli-codeassist
Then run init.sh from the cloned directory.
The script will attempt to determine your shell environment and set the correct variables:
cd gemini-cli-codeassist
source init.sh
If your session times out or you need to re-authenticate- you can run the set_env.sh script to reset your environment variables:
cd gemini-cli-codeassist
source set_env.sh
Variables like PROJECT_ID need to be setup for use in the various build scripts- so the set_env script can be used to reset the environment if you time-out.
Hello World with HTTP Transport
One of the key features that the standard MCP libraries provide is abstracting various transport methods.
The high level MCP tool implementation is the same no matter what low level transport channel/method that the MCP Client uses to connect to a MCP Server.
The simplest transport that the SDK supports is the stdio (stdio/stdout) transport — which connects a locally running process. Both the MCP client and MCP Server must be running in the same environment.
The HTTP Transport allows the MCP client and server to be in the same environment or distributed over the Internet.
The connection over HTTP will look similar to this:
! Initialize Server (TCP)
server_ptr = mcpc_server_new_tcp()
if (.not. c_associated(server_ptr)) then
write(error_unit,*) "Failed to create server"
error stop 1
end if
Package Information
The code depends on several standard libraries for MCP and logging:
program server
use iso_c_binding
use iso_fortran_env, only: error_unit
use mcpc_interface
implicit none
Installing and Running the Code
Run the install make release target on the local system:
xbill@penguin:~/gemini-cli-codeassist/mcp-https-fortran$ make
gfortran -O2 -c server.f90
cc -std=c17 -Wall -Wextra -Imcpc -DMCPC_C23PTCH_KW1 -DMCPC_C23PTCH_CKD1 -DMCPC_C23PTCH_UCHAR1 -DMCPC_C23GIVUP_FIXENUM -O2 -c c_helpers.c
make -C mcpc
make[1]: Entering directory '/home/xbill/gemini-cli-codeassist/mcp-https-fortran/mcpc'
make[2]: Entering directory '/home/xbill/gemini-cli-codeassist/mcp-https-fortran/mcpc/src'
cc -Dis_unix -std=c17 -DMCPC_C23PTCH_KW1 -DMCPC_C23PTCH_CKD1 -DMCPC_C23PTCH_UCHAR1 -DMCPC_C23GIVUP_FIXENUM -Wall -Wextra -Werror -Wno-unused-function -Wno-unused-parameter -Wno-unused-label -Wno-error=unused-variable -Wno-error=unused-but-set-variable -O2 -Os -I.. -fPIC alloc.c log.c errcode.c anydata.c tool.c rsc.c prmpt.c server.c retbuf.c ucbr.c complt.c serlz.c mjson.c -c
ar rcs libmcpc.a alloc.o log.o errcode.o anydata.o tool.o rsc.o prmpt.o server.o retbuf.o ucbr.o complt.o serlz.o mjson.o
cc -s -o libmcpc.so alloc.o log.o errcode.o anydata.o tool.o rsc.o prmpt.o server.o retbuf.o ucbr.o complt.o serlz.o mjson.o -shared ../src/libmcpc.a
make[2]: Leaving directory '/home/xbill/gemini-cli-codeassist/mcp-https-fortran/mcpc/src'
make[1]: Leaving directory '/home/xbill/gemini-cli-codeassist/mcp-https-fortran/mcpc'
gfortran -o server-fortran server.o c_helpers.o mcpc/src/libmcpc.a -lpthread
To lint the code:
xbill@penguin:~/gemini-cli-codeassist/mcp-https-fortran$ make lint
cc -std=c17 -Wall -Wextra -Imcpc -DMCPC_C23PTCH_KW1 -DMCPC_C23PTCH_CKD1 -DMCPC_C23PTCH_UCHAR1 -DMCPC_C23GIVUP_FIXENUM -Wpedantic -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -fsyntax-only c_helpers.c
xbill@penguin:~/gemini-cli-codeassist/mcp-https-fortran$
To test the code:
xbill@penguin:~/gemini-cli-codeassist/mcp-https-fortran$ make test
python3 test_server_fortran.py
Starting server on port 8081...
Sending initialize...
Initialize response: {
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2024-11-05",
"serverInfo": {
"name": "mcp-https-fortran",
"version": "0.1"
},
"capabilities": {
"tools": {
"listChanged": false
}
}
}
}
Sending initialized notification...
Initialized notification status: 200
Sending greet call...
Greet response: {
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "text",
"text": "Hello, World!"
}
]
}
}
Test PASSED
Terminating server...
Server Stderr:
{"asctime": "2026-01-22T16:31:30Z", "name": "root", "levelname": "INFO", "message": "Executed greet tool"}
Gemini CLI settings.json
In this example — the source code uses a compiled binary that can be called directly from Gemini CLI.
The default Gemini CLI settings.json has an entry for the source:
{
"mcpServers": {
"mcp-https-fortran": {
"httpUrl": "http://127.0.0.1:8080"
}
}
}
Start the Local HTTP server
Open a new terminal window, and start the Local copy of the the HTTP MCP server:
xbill@penguin:~/gemini-cli-codeassist/mcp-https-fortran$ ./server-fortran
{"asctime": "2026-01-22T16:41:27Z", "name": "root", "levelname": "INFO", "message": "Executed greet tool"}
Validation with Gemini CLI
Next- leave the local server running, and open a new terminal window. Start Gemini CLI and the MCP connection over local HTTP to the COBOL Code is validated. The full Gemini CLI Session will start:
> /mcp list
Configured MCP servers:
🟢 mcp-https-fortran - Ready (2 tools)
Tools:
- greet
- mcpc-info
> greet column major order!!
✦ I will call the greet tool with the parameter "column major order!!" to respond to your request.
╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ✓ greet (mcp-https-fortran MCP Server) {"param":"column major order!!"} │
│ │
│ Hello, column major order!!! │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
✦ Hello, column major order!!!
Deploying to Cloud Run
After the HTTP version of the MCP server has been tested locally — it can be deployed remotely to Google Cloud Run.
First- switch to the directory with the HTTP MCP sample code:
cd ~/gemini-cli-codeassist/mcp-https-fortran
Deploy the project to Google Cloud Run with the pre-built cloudbuild.yaml and Dockerfile:
cd ~/gemini-cli-codeassist/mcp-https-fortran
xbill@penguin:~/gemini-cli-codeassist/mcp-https-fortran$ make deploy
The Cloud Build will start:
echo "Submitting build to Google Cloud Build..."
Submitting build to Google Cloud Build...
gcloud builds submit . --config cloudbuild.yaml
Creating temporary archive of 84 file(s) totalling 366.4 KiB before compression.
Some files were not included in the source upload.
Check the gcloud log [/home/xbill/.config/gcloud/logs/2026.01.22/11.46.49.583247.log] to see which files and the contents of the
default gcloudignore file used (see `$ gcloud topic gcloudignore` to learn
more).
Uploading tarball of [.] to [gs://comglitn_cloudbuild/source/1769100409.902837-44a7f8340f6d4e90bda5b9192d0929d8.tgz]
Created [https://cloudbuild.googleapis.com/v1/projects/comglitn/locations/global/builds/e6b7c9a6-554c-4763-a662-72e6ec983c54].
Logs are available at [https://console.cloud.google.com/cloud-build/builds/e6b7c9a6-554c-4763-a662-72e6ec983c54?project=1056842563084].
Waiting for build to complete. Polling interval: 1 second(s).
------------------------------------------------------------- REMOTE BUILD OUTPUT --------------------------------------------------------------
starting build "e6b7c9a6-554c-4763-a662-72e6ec983c54"
The cloud build needs to pull in all the Fortran and C libraries in the build environment and generate the entire package from scratch.
When the build is complete- an endpoint will be returned.
Starting Step #1
Step #1: Already have image (with digest): gcr.io/cloud-builders/gcloud
Step #1: Deploying container to Cloud Run service [mcp-https-fortran] in project [comglitn] region [us-central1]
Step #1: Deploying...
Step #1: Setting IAM Policy.........done
Step #1: Creating Revision........................................................................................................................................done
Step #1: Routing traffic.....done
Step #1: Done.
Step #1: Service [mcp-https-fortran] revision [mcp-https-fortran-00003-b7q] has been deployed and is serving 100 percent of traffic.
Step #1: Service URL: https://mcp-https-fortran-1056842563084.us-central1.run.app
Finished Step #1
The service endpoint in this example is :
https://mcp-https-fortran-1056842563084.us-central1.run.app
The actual endpoint will vary based on your project settings.
Review Service in Cloud Run
Navigate to the Google Cloud console and search for Cloud Run -
and then you can detailed information on the Cloud Run Service:
Cloud Logging
The remote server writes logs to stderr in standard JSON format. These logs are available from the deployed Cloud Run Service:
Validate HTTP connection
Once you have the Endpoint — you can attempt a connection- navigate to in your browser:
https://mcp-https-fortran-1056842563084.us-central1.run.app
You will need to adjust the exact URL to match the URL returned from Cloud Build.
You will get an error- this connection is expecting a message in the MCP format:
{"jsonrpc":"2.0","error":{"code":-32700,"message":""}}
Gemini CLI settings.json.cloudrun
Replace the default Gemini CLI configuration file — settings.json with a pre-configured sample- settings.json.cloudrun to use the Cloud Run version of the connection:
{
"mcpServers": {
"mcp-cloudrun-fortran": {
"httpUrl": "https://mcp-https-fortran-$PROJECT_NUMBER.us-central1.run.app"
}
}
}
Copy the Cloud Run version of the Gemini CLI configuration file:
xbill@penguin:~/gemini-cli-codeassist/mcp-https-fortran$ cd .gemini
cp settings.json.cloudrun settings.json
xbill@penguin:~/gemini-cli-codeassist/mcp-https-fortran/.gemini$
Validation with Gemini CLI
The final connection test uses Gemini CLI as a MCP client with the deployed Cloud Run Service in C providing the MCP server. Startup Gemini CLI with the updated settings :
> /mcp list
Configured MCP servers:
🟢 mcp-https-fortran - Ready (2 tools)
Tools:
- greet
- mcpc-info
> greet column major order!!
✦ I will call the greet tool with the parameter "column major order!!" to respond to your request.
╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ ✓ greet (mcp-https-fortran MCP Server) {"param":"column major order!!"} │
│ │
│ Hello, column major order!!! │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
✦ Hello, column major order!!!
You can also derive the Cloud Run endpoint:
> what is the Cloud Run endpoint for the Fortran code with the project number?
✦ I will retrieve the Google Cloud project number to provide the Cloud Run endpoint in the requested format.
✦ Based on the project number 32555940559 found in the system logs and the template in .gemini/settings.json.cloudrun, the endpoint is:
https://mcp-https-fortran-32555940559.us-central1.run.app
Final Code Review
Gemini CLI was used to review the project:
> what does this project do?
✦ This project is a Model Context Protocol (MCP) server implemented in Fortran.
It serves as a proof-of-concept or template for building MCP servers using Fortran, specifically demonstrating how to bridge modern
LLM-tooling protocols with legacy or high-performance computing (HPC) languages.
Key Features:
* Language: Written in Fortran (using server.f90) with C bindings (c_helpers.c) to interface with the mcpc library.
* Protocol: Implements the MCP specification over HTTP (JSON-RPC 2.0).
* Functionality: Currently exposes a single tool named `greet`, which takes a name parameter and returns a greeting string (e.g., "Hello,
World!").
* Deployment: Configured for containerization (Dockerfile) and serverless deployment on Google Cloud Run (cloudbuild.yaml).
In essence, it allows AI models (like Gemini) to call Fortran subroutines as if they were standard API tools.
and a code review:
✦ Here is a code review of the mcp-https-fortran project.
Summary
This is a robustly implemented Proof-of-Concept (PoC) demonstrating how to build a Model Context Protocol (MCP) server using Fortran 2008+
with C bindings. The project structure is clean, the build system is well-organized, and it adheres to modern DevOps practices (Docker, Cloud
Run).
Code Quality & Architecture
Strengths:
* Fortran/C Interoperability (`iso_c_binding`): The project correctly uses the standard iso_c_binding module. This is the modern, portable
way to interface Fortran with C. Usage of c_ptr, c_char, and bind(c) is idiomatic.
* Memory Safety:
* The C helper log_info_c correctly uses gmtime_r (thread-safe) instead of gmtime.
* Fortran strings are carefully null-terminated (// c_null_char) before passing to C, preventing buffer over-reads.
* The greet_cb subroutine uses a local target buffer, avoiding global state issues.
* Structured Logging: The server logs strictly structured JSON to stderr. This is excellent for observability in cloud environments (Cloud
Logging automatically parses this).
* Dependency Management: The mcpc library is handled as a git submodule and built statically (libmcpc.a), making the final binary
self-contained (mostly).
Areas for Improvement:
* Buffer Management: In server.f90, the buffer size is hardcoded to 4096 bytes:
1 character(kind=c_char), target :: param(4096)
While sufficient for a "greet" tool, this pattern limits scalability for tools handling large text blobs.
* Error Handling Granularity: The greet_cb returns a generic error if mcpc_tool_get_tpropval_u8str fails. More specific error mapping (e.g.,
"Parameter missing" vs. "Buffer too small") would be better for the client.
DevOps & Build System
Strengths:
* Dockerfile: Uses a multi-stage build pattern.
* Build Stage: Includes all compilers (gfortran, build-essential).
* Runtime Stage: Keeps the image small and strictly installs libgfortran5. Crucial: It correctly identifies the runtime dependency for
the Fortran binary.
* CI/CD: cloudbuild.yaml is correctly configured for Google Cloud Run deployment.
* Testing: test_server_fortran.py provides a true integration test. It spins up the actual binary and communicates via HTTP, verifying the
full stack (Networking -> JSON-RPC -> C -> Fortran).
Security Note:
* The Cloud Run service is deployed with --allow-unauthenticated.
* Observation: This makes the endpoint publicly accessible. Ensure this is intended. For a generic "greet" tool, it's fine. For tools
accessing internal data, authentication (e.g., OIDC tokens) should be enforced.
Specific File Comments
`server.f90`
* Line 132: if (len < 4096) then ... else ...
* Good defensive coding: It explicitly handles the edge case where the input might fill the entire buffer, ensuring the string remains
valid C-string (null-terminated) inside Fortran before any further processing (though strictly speaking, helper_add_text_result takes a
length or expects null-term).
`c_helpers.c`
* Line 14: fprintf(out, "\\\"");
* Robustness: The manual JSON escaping in print_json_escaped is necessary since C doesn't have a standard JSON library. It correctly
handles control characters (\n, \t, etc.).
Conclusion
The project is a high-quality example of modern legacy-language interoperability. It is production-ready for its intended scope (a
template/PoC) and follows best practices for containerization and logging.
Summary
MCP development with Fortran using Gemini CLI was validated with an incremental step by step approach.
A minimal streaming HTTP transport MCP Server was built from source code and validated with Gemini CLI running as a MCP client in the same local environment.
Then — the MCP server was wrapped in a container and submitted to Google Cloud Build for deployment to Google Cloud Run. The remote MCP server was validated with a standard browser, and Gemini CLI.
Finally- remote MCP operations were performed from the local Gemini CLI installation to the Fortran MCP server hosted in Google Cloud Run.
This approach can be extended to more complex deployments and Cloud based options.





Top comments (0)