#
tokens: 1750/50000 5/5 files
lines: off (toggle) GitHub
raw markdown copy
# Directory Structure

```
├── .gitignore
├── docs
│   └── mcp-inspector.png
├── pyproject.toml
├── README.md
└── src
    └── mcp_sbom
        ├── __init__.py
        ├── sbom.json
        └── server.py
```

# Files

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

.python-version

# UV
uv.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can
#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
#  and can be added to the global gitignore or merged into this file.  For a more nuclear
#  option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

# Ruff stuff:
.ruff_cache/

# PyPI configuration file
.pypirc

```

--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------

```markdown
# MCP SBOM Server

[![Python](https://img.shields.io/badge/Python-3.12-blue.svg)](https://www.python.org/)
[![MCP](https://img.shields.io/badge/MCP-1.6-CC5500.svg)](https://www.anthropic.com/news/model-context-protocol)

MCP server to perform a Trivy scan and produce an SBOM in CycloneDX format.

## Installation

### Prerequisites

Install the following.

- [uv](https://github.com/astral-sh/uv)
- [trivy](https://github.com/aquasecurity/trivy)
- [Node.js](https://nodejs.org/en)

## MCP Clients

### Configuration

```json
"mcpServers": {
        "mcp-sbom": {
            "command": "uv",
            "args": [
                "--directory",
                "/path/to/mcp-sbom",
                "run",
                "mcp-sbom"
            ]
        }
    }
```

## Building

> [!NOTE]
> This project employs `uv`.

1. Synchronize dependencies and update the lockfile.
```
uv sync
```

## Debugging

### MCP Inspector

Use [MCP Inspector](https://github.com/modelcontextprotocol/inspector).

Launch the MCP Inspector as follows:

```
npx @modelcontextprotocol/inspector uv --directory /path/to/mcp-sbom run mcp-sbom
```

![MCP Inspector](docs/mcp-inspector.png)

### Windows

When running on Windows, use paths of the style:

```console
C:/Users/gkh/src/mcp-sbom-server/src/mcp_sbom
```

```

--------------------------------------------------------------------------------
/src/mcp_sbom/__init__.py:
--------------------------------------------------------------------------------

```python
from . import server
import asyncio

def main():
    """Main entry point for the package."""
    asyncio.run(server.main())

__all__ = [ 'main', 'server' ]
```

--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------

```toml
[project]
name = "mcp-sbom"
version = "0.1.0"
description = "MCP server to perform a scan and produce an SBOM"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
    "mcp[cli]>=1.6.0",
    "python-dotenv>=1.0.1",
]

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[dependency-groups]
dev = [
    "pyright>=1.1.389",
]

[project.scripts]
mcp-sbom = "mcp_sbom:main"
```

--------------------------------------------------------------------------------
/src/mcp_sbom/server.py:
--------------------------------------------------------------------------------

```python
import asyncio
import json
import logging
from mcp.server.fastmcp import FastMCP

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("mcp-sbom")

mcp = FastMCP("mcp-sbom")

async def exec_trivy(image: str):
    try:
        logger.info(f"Starting Trivy scan for image: {image}")
        cmd = [
            "trivy", "image", 
            "--format", "cyclonedx", 
            "--output", "sbom.json", 
            image
            ]
        # result = subprocess.run(cmd, capture_output=True, text=True)
        process = await asyncio.create_subprocess_exec(
            *cmd, 
            stdout=asyncio.subprocess.PIPE, 
            stderr=asyncio.subprocess.PIPE
            )
        stdout, stderr = await process.communicate()
        logger.info(f"Trivy scan completed with return code {process.returncode}")
        
        if process.returncode == 0:
            with open("sbom.json", "r") as f:
                sbom_content = json.load(f)
        return sbom_content
    except Exception as e:
        logger.error(f"Exception in exec_trivy: {str(e)}")
        return f"Error: {str(e)}"

@mcp.tool()
async def scan(image: str):
    """
    Execute Trivy scanner to generate SPDX SBOM for a container image.
    Supports the SPDX JSON format.

    Args:
        image (str): The container image name/reference to scan

    Returns:
        str: Test response or error message
    """
    try:
        logger.info(f"MCP SBOM tool called with image: {image}")
        result = await exec_trivy(image)
        logger.debug(f"Trivy execution result: {result}")
        return result
    except Exception as e:
        logger.error(f"Exception in trivy tool: {str(e)}")
        return f"Error: {str(e)}"

# if __name__ == "__main__":
def main():
    logger.info("Starting SBOM MCP Server!")

    try:
        mcp.run(transport="stdio")
    except Exception as e:
        logger.error(f"Error running MCP server: {str(e)}")

```