Skip to content

Add MCP server skeleton - #1

Open
avikalpg wants to merge 1 commit into
mainfrom
codex/build-mcp-server-for-code-categorization-and-validation
Open

Add MCP server skeleton#1
avikalpg wants to merge 1 commit into
mainfrom
codex/build-mcp-server-for-code-categorization-and-validation

Conversation

@avikalpg

@avikalpg avikalpg commented Jun 13, 2025

Copy link
Copy Markdown
Contributor

Summary

  • add a basic FastAPI server that checks if a code request needs a PRD
  • implement request categorisation and PRD validation
  • document server usage in README

Testing

  • pytest -q

https://chatgpt.com/codex/tasks/task_e_684b93fe12088331ba68aef7e7f47d79

Summary by CodeRabbit

  • New Features

    • Introduced a server that categorizes software development requests and collects product requirements before code generation.
    • Added REST endpoints to detect request intent, categorize requests, and validate product requirement document submissions.
  • Documentation

    • Expanded the README with detailed project description, usage instructions, and endpoint explanations.

@coderabbitai

coderabbitai Bot commented Jun 13, 2025

Copy link
Copy Markdown

Walkthrough

A FastAPI server named "MCP Server" was introduced to intercept code generation requests and enforce the collection of a product requirements document (PRD) before proceeding. The README was expanded to fully describe the project, endpoints, and usage instructions, while the server implements categorization and validation logic for software development requests.

Changes

File(s) Change Summary
README.md Expanded with detailed project description, endpoint documentation, and local running instructions.
mcp_server.py Added FastAPI server with endpoints for request categorization and PRD submission/validation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MCP_Server

    User->>MCP_Server: POST /request-category (description)
    MCP_Server->>MCP_Server: Detects if request is code modification
    MCP_Server->>MCP_Server: Categorizes request and determines PRD fields
    MCP_Server-->>User: Returns category and required PRD fields

    User->>MCP_Server: POST /submit-prd (category, fields)
    MCP_Server->>MCP_Server: Validates PRD completeness
    alt PRD complete
        MCP_Server-->>User: Returns accepted: true
    else PRD incomplete
        MCP_Server-->>User: HTTP 400 error
    end
Loading

Poem

In the warren, code requests now pause,
For PRDs are gathered, with nary a clause.
The server listens, wise and neat—
Categorizing tasks before code’s heartbeat.
🐇 FastAPI hops, endpoints in tow,
Requirements in paw, onward we go!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
README.md (1)

18-21: Prefer uvicorn CLI over running the module directly

Running the server via python mcp_server.py works, but using the dedicated ASGI server entry point is more idiomatic and enables hot-reload in development:

-pip install fastapi uvicorn pydantic
-python mcp_server.py
+pip install "fastapi[all]" uvicorn pydantic
+uvicorn mcp_server:app --reload

This also avoids importing uvicorn at runtime when the file is executed as a script.

mcp_server.py (2)

88-98: Return the Enum’s value to keep the public JSON schema stable

Although FastAPI serialises Enums automatically, being explicit avoids surprises if the implementation detail changes and keeps the OpenAPI spec cleaner.

-    return {
-        "requires_action": True,
-        "category": category,
-        "required_fields": list(template.keys()),
-    }
+    return {
+        "requires_action": True,
+        "category": category.value,
+        "required_fields": list(template.keys()),
+    }

100-105: Surface which fields are missing instead of a generic 400

Returning granular feedback makes the endpoint easier to use programmatically.

-    if not prd_complete(submission.category, submission.fields):
-        raise HTTPException(status_code=400, detail="Incomplete PRD fields")
+    missing = [
+        f for f in PRD_TEMPLATES[submission.category]
+        if not submission.fields.get(f, "").strip()
+    ]
+    if missing:
+        raise HTTPException(
+            status_code=400,
+            detail=f"Missing/empty PRD fields: {', '.join(missing)}",
+        )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2503951 and 43b527e.

📒 Files selected for processing (2)
  • README.md (1 hunks)
  • mcp_server.py (1 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
mcp_server.py

[refactor] 51-51: Too few public methods (0/2)

(R0903)


[refactor] 54-54: Too few public methods (0/2)

(R0903)

Comment thread mcp_server.py
Comment on lines +66 to +76
def categorize_request(text: str) -> RequestCategory:
text = text.lower()
if any(k in text for k in ["bug", "defect"]):
return RequestCategory.BUG_REPORT
if any(k in text for k in ["error", "crash"]):
return RequestCategory.ERROR_REPORT
if "enhancement" in text or "improve" in text:
return RequestCategory.FEATURE_ENHANCEMENT
if any(k in text for k in ["new feature", "feature"]):
return RequestCategory.NEW_FEATURE
return RequestCategory.OTHER

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

String containment may mis-categorise; use word boundaries & consolidate heuristics

Current checks will treat “debug” as a bug or “featureless” as a feature. Refactor to bounded regexes and a single dictionary-driven approach for maintainability.

-def categorize_request(text: str) -> RequestCategory:
-    text = text.lower()
-    if any(k in text for k in ["bug", "defect"]):
-        return RequestCategory.BUG_REPORT
-    if any(k in text for k in ["error", "crash"]):
-        return RequestCategory.ERROR_REPORT
-    if "enhancement" in text or "improve" in text:
-        return RequestCategory.FEATURE_ENHANCEMENT
-    if any(k in text for k in ["new feature", "feature"]):
-        return RequestCategory.NEW_FEATURE
-    return RequestCategory.OTHER
+_CATEGORY_PATTERNS = {
+    RequestCategory.BUG_REPORT:      re.compile(r"\b(bug|defect)\b", re.I),
+    RequestCategory.ERROR_REPORT:    re.compile(r"\b(error|crash)\b", re.I),
+    RequestCategory.FEATURE_ENHANCEMENT: re.compile(r"\b(enhancement|improve)\b", re.I),
+    RequestCategory.NEW_FEATURE:     re.compile(r"\bnew feature\b|\bfeature\b", re.I),
+}
+
+def categorize_request(text: str) -> RequestCategory:
+    for cat, rx in _CATEGORY_PATTERNS.items():
+        if rx.search(text):
+            return cat
+    return RequestCategory.OTHER

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In mcp_server.py around lines 66 to 76, the current string containment checks
can misclassify words like "debug" as bugs or "featureless" as features.
Refactor the function to use regex with word boundaries for each keyword to
ensure exact word matches. Consolidate all category keywords into a single
dictionary mapping categories to their regex patterns, then iterate over this
dictionary to find matches, improving maintainability and accuracy.

Comment thread mcp_server.py
Comment on lines +59 to +64
def detect_modification_request(text: str) -> bool:
"""Very naive check for whether the user wants code changes."""
keywords = ["add", "create", "fix", "update", "modify", "implement", "code"]
pattern = r"|".join(keywords)
return bool(re.search(pattern, text, re.IGNORECASE))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Regex will match unintended words such as ‘address’, ‘addition’, etc.

Add word-boundaries and pre-compile the pattern to cut false positives and save per-request compilation overhead.

-keywords = ["add", "create", "fix", "update", "modify", "implement", "code"]
-pattern = r"|".join(keywords)
-return bool(re.search(pattern, text, re.IGNORECASE))
+_MOD_PATTERN = re.compile(
+    r"\b(add|create|fix|update|modify|implement|code)\b",
+    flags=re.IGNORECASE,
+)
+return bool(_MOD_PATTERN.search(text))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def detect_modification_request(text: str) -> bool:
"""Very naive check for whether the user wants code changes."""
keywords = ["add", "create", "fix", "update", "modify", "implement", "code"]
pattern = r"|".join(keywords)
return bool(re.search(pattern, text, re.IGNORECASE))
def detect_modification_request(text: str) -> bool:
"""Very naive check for whether the user wants code changes."""
_MOD_PATTERN = re.compile(
r"\b(add|create|fix|update|modify|implement|code)\b",
flags=re.IGNORECASE,
)
return bool(_MOD_PATTERN.search(text))
🤖 Prompt for AI Agents
In mcp_server.py around lines 59 to 64, the regex pattern matches unintended
words like 'address' or 'addition' because it lacks word boundaries. Modify the
pattern to include word boundaries around each keyword to ensure exact word
matches. Additionally, pre-compile the regex pattern outside the function to
avoid recompiling it on every call, improving performance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant