Skip to content

add initial server with run and codebase initialization #507

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 34 commits into from
Feb 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
6c64ab2
fix: add initial server with run and codebase initialization
rushilpatel0 Feb 14, 2025
b68153b
Automated pre-commit update
rushilpatel0 Feb 14, 2025
538418e
nit: update toml
rushilpatel0 Feb 18, 2025
e8fcb04
[CG-10829] fix: import wildcard doesn't preserve import resolution (#…
Feb 14, 2025
db5d9aa
docs: fix initialization (#504)
kopekC Feb 14, 2025
c3f7474
feat: adds linear tools (#499)
jayhack Feb 14, 2025
e23d8ac
feat: search_linear and create_linear tools (#508)
jayhack Feb 15, 2025
ebbfc14
chore: better tools arrangement (#509)
jayhack Feb 15, 2025
8581a93
feat: BashCommandTool (#510)
jayhack Feb 15, 2025
1a341bd
fix(deps): update dependency pygithub to v2.6.0 (#513)
renovate[bot] Feb 15, 2025
08624ae
Codebase Analytics Dashboard Tutorial (#511)
vishalshenoy Feb 15, 2025
a75991b
fix: deep code research (#512)
jayhack Feb 15, 2025
ec2ef11
docs: docs research agent (#514)
jayhack Feb 15, 2025
c8e3a20
Update build-code-agent.mdx
jayhack Feb 16, 2025
8f9db9b
feat: slack webhook handler (#516)
jayhack Feb 16, 2025
93a7635
Fixing links to examples in tutorials (#515)
vishalshenoy Feb 16, 2025
57ead4b
docs: agent docs hotfix (#517)
jayhack Feb 16, 2025
4063bc5
Update overview.mdx
jayhack Feb 16, 2025
27f0899
Update deep-code-research.mdx
jayhack Feb 16, 2025
e913729
feat: enables github webhooks (#518)
jayhack Feb 16, 2025
f7ee186
fix: relaxes gh types (#519)
jayhack Feb 16, 2025
2f864d9
feat: agent cli (#520)
jayhack Feb 16, 2025
3a60bda
chore(deps): lock file maintenance (#524)
renovate[bot] Feb 17, 2025
fa95ae6
fix(deps): update dependency openai to v1.63.1 (#435)
renovate[bot] Feb 17, 2025
a8125b4
fix(deps): update dependency sentry-sdk to v2.22.0 (#436)
renovate[bot] Feb 17, 2025
2bac505
fix(deps): update dependency openai to v1.63.2 (#526)
renovate[bot] Feb 17, 2025
5d8f3fb
Remove Permalink (#525)
vishalshenoy Feb 17, 2025
5b48892
feat: vector index refactor (#528)
jayhack Feb 17, 2025
1ebb084
Automated pre-commit update
rushilpatel0 Feb 18, 2025
3549887
update pyproject script
rushilpatel0 Feb 18, 2025
cfd864a
Merge branch 'develop' into rpatel/mcp-server-example
rushilpatel0 Feb 18, 2025
429752e
Automated pre-commit update
rushilpatel0 Feb 18, 2025
95fccae
fix: update readme
rushilpatel0 Feb 18, 2025
8753193
Automated pre-commit update
rushilpatel0 Feb 18, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions codegen-examples/examples/codegen-mcp-server/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Codegen MCP Server

<p align="center">
<a href="https://docs.codegen.com">
<img src="https://i.imgur.com/6RF9W0z.jpeg" />
</a>
</p>

<h2 align="center">
An MCP server implementation that integrates the codegen sdk.

</h2>

<div align="center">

[![Documentation](https://img.shields.io/badge/Docs-docs.codegen.com-purple?style=flat-square)](https://docs.codegen.com)
[![License](https://img.shields.io/badge/Code%20License-Apache%202.0-gray?&color=gray)](https://github.com/codegen-sh/codegen-sdk/tree/develop?tab=Apache-2.0-1-ov-file)

</div>

This example demonstrates how to run a Model Control Protocol (MCP) server that integrates with Codegen. The server provides:

1. A standardized interface for model inference
1. Integration with Codegen's core functionality, parsing codebases and executing codemods
1. Support for various LLM providers through the MCP protocol

## Quick Start

### Prerequisites

- [uv](https://docs.astral.sh/uv/getting-started/installation/)
- [python](https://www.python.org/downloads/) 3.12+

### Direct Execution

1. No installation is necessary, with the following command. Run this command directly or add it your `.json` mcp config file.

```bash
uvx --from 'git+https://github.com/codegen-sh/codegen-sdk.git@ce8cffe#egg=codegen-mcp-server&subdirectory=codegen-examples/examples/codegen-mcp-server' codegen-mcp-server
```

### Example MCP Config

Here is an example mcp config that can be used with Cline or Claude desktop to integrate this MCP server

```json
{
"mcpServers": {
"codegen-mcp": {
"command": "uvx",
"args": [
"--from",
"git+https://github.com/codegen-sh/codegen-sdk.git#egg=codegen-mcp-server&subdirectory=codegen-examples/examples/codegen-mcp-server",
"codegen-mcp-server"
],
"disabled": false,
"autoApprove": []
}
}
}
```

###MCP Tools:

- `parse_codebase`: Parses a codebase located at the provided path.
- `check_parse_status`: Provides the current parsing status for the provided codebase.
- `execute_codemod`: Executes a codemod script on a parsed codebase. This is where the codegen sdk leveraged to run simple or sophisticated codemods on the codebase.
20 changes: 20 additions & 0 deletions codegen-examples/examples/codegen-mcp-server/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[project]
name = "codegen-mcp-server"
version = "0.1.0"
description = "MCP server implementation adding tools for the Codegen SDK"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"codegen>=0.14.5",
"uvicorn>=0.27.1",
"fastapi>=0.110.0",
"pydantic>=2.6.3",
"rich>=13.7.1",
"click>=8.1.7",
"mcp[cli]>=1.2.1",
]

[tool.poetry.scripts]
codegen-mcp-server = "server:main"
[project.scripts]
codegen-mcp-server = "server:main"
93 changes: 93 additions & 0 deletions codegen-examples/examples/codegen-mcp-server/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import asyncio
from dataclasses import dataclass, field
from typing import Annotated, Optional, Dict, Any, List
from mcp.server.fastmcp import FastMCP
from codegen import Codebase


@dataclass
class CodebaseState:
"""Class to manage codebase state and parsing."""

parse_task: Optional[asyncio.Task] = None
parsed_codebase: Optional[Codebase] = None
log_buffer: List[str] = field(default_factory=list)

async def parse(self, path: str) -> Codebase:
"""Parse the codebase at the given path."""
codebase = Codebase(path)

Check failure on line 18 in codegen-examples/examples/codegen-mcp-server/server.py

View workflow job for this annotation

GitHub Actions / mypy

error: Need type annotation for "codebase" [var-annotated]
self.parsed_codebase = codebase
return codebase

def reset(self) -> None:
"""Reset the state."""
if self.parsed_codebase:
self.parsed_codebase.reset()
self.log_buffer.clear()


# Initialize FastMCP server
mcp = FastMCP(
"codegen-mcp-server",
instructions="""This server provides tools to parse and modify a codebase using codemods.
It can initiate parsing, check parsing status, and execute codemods.""",
)

# Initialize state
state = CodebaseState()


def capture_output(*args, **kwargs) -> None:
"""Capture and log output messages."""
for arg in args:
state.log_buffer.append(str(arg))


@mcp.tool(name="parse_codebase", description="Initiate codebase parsing")
async def parse_codebase(codebase_path: Annotated[str, "path to the codebase to be parsed"]) -> Dict[str, str]:
if not state.parse_task or state.parse_task.done():
state.parse_task = asyncio.create_task(state.parse(codebase_path))
return {"message": "Codebase parsing initiated, this may take some time depending on the size of the codebase. Use the `check_parsing_status` tool to check if the parse has completed."}
return {"message": "Codebase is already being parsed."}


@mcp.tool(name="check_parse_status", description="Check if codebase parsing has completed")
async def check_parse_status() -> Dict[str, str]:
if not state.parse_task:
return {"message": "No codebase provided to parse."}
if state.parse_task.done():
return {"message": "Codebase parsing completed."}
return {"message": "Codebase parsing in progress."}


@mcp.tool(name="execute_codemod", description="Execute a codemod on the codebase")
async def execute_codemod(codemod: Annotated[str, "The python codemod code to execute on the codebase"]) -> Dict[str, Any]:
if not state.parse_task or not state.parse_task.done():
return {"error": "Codebase is not ready for codemod execution."}

try:
await state.parse_task
# TODO: Implement proper sandboxing for code execution
context = {
"codebase": state.parsed_codebase,
"print": capture_output,
}
exec(codemod, context)

logs = "\n".join(state.log_buffer)

state.reset()
return {"message": "Codemod executed and codebase reset.", "logs": logs}
except Exception as e:
return {"error": f"Error executing codemod: {str(e)}", "details": {"type": type(e).__name__, "message": str(e)}}


def main():
print("starting codegen-mcp-server")
run = mcp.run_stdio_async()
print("codegen-mcp-server started")
asyncio.run(run)


if __name__ == "__main__":
main()
Loading
Loading