Skip to content
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

refactor(torii-server): mcp and sql cleanup with instructions static file #2790

Merged
merged 1 commit into from
Dec 10, 2024

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Dec 10, 2024

Summary by CodeRabbit

  • New Features

    • Introduced dedicated methods for handling specific JSON-RPC requests, enhancing request processing.
    • Added a new function for converting SQL rows to JSON, improving data handling.
    • Launched a comprehensive documentation file for the Torii indexer, detailing its functionalities and usage.
  • Bug Fixes

    • Centralized error handling for invalid requests, standardizing response formats.

Copy link

coderabbitai bot commented Dec 10, 2024

Walkthrough

Ohayo! This pull request introduces significant refactoring in the McpHandler implementation within the mcp.rs file, focusing on modularizing request handling through dedicated methods for specific JSON-RPC actions. It also centralizes error handling in the JsonRpcResponse struct. Additionally, a new function for converting SQL rows to JSON is added in sql.rs, and a comprehensive documentation file for the Torii indexer is introduced, detailing its functionalities and usage.

Changes

File Path Change Summary
crates/torii/server/src/handlers/mcp.rs - Refactored McpHandler to include methods: handle_initialize, handle_tools_list, handle_tools_call.
- Simplified handle_request to delegate to new methods.
- Centralized error handling with new methods in JsonRpcResponse.
- Updated handle_query_tool to expect parameters under arguments.
- Removed inline comments; added static instruction file for initialize.
crates/torii/server/src/handlers/sql.rs - Added map_row_to_json function for converting SQL rows to JSON, replacing inline logic in execute_query.
crates/torii/server/static/mcp-instructions.txt - Introduced documentation for the Torii indexer, detailing its purpose, features, and usage examples.

Possibly related PRs

  • feat(torii-server): add MCP service to torii ✨ #2778: The changes in this PR involve the addition of the McpHandler, which is directly related to the modifications made in the main PR regarding the McpHandler implementation in mcp.rs. Both PRs focus on enhancing the handling of JSON-RPC requests within the MCP context.

Suggested reviewers

  • glihm

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Experiment)
  • @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.

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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
crates/torii/server/static/mcp-instructions.txt (2)

7-7: Typographical Correction: Duplicate Word

Ohayo sensei! In line 7, there is a duplicated word "data":

- dynamic model tables: Stores model data data associated with entities

Please remove the extra word:

- dynamic model tables: Stores model data associated with entities
🧰 Tools
🪛 LanguageTool

[duplication] ~7-~7: Possible typo: you repeated a word
Context: ...te - dynamic model tables: Stores model data data associated with entities - models: Cont...

(ENGLISH_WORD_REPEAT_RULE)


14-14: Grammar Suggestion: Insert Comma for Clarity

Ohayo sensei! In line 14, consider inserting a comma after "schema" to improve readability:

Original:

You should always retrieve the schema if unsure about how to query the database.

Revised:

You should always retrieve the schema, if unsure about how to query the database.
🧰 Tools
🪛 LanguageTool

[formatting] ~14-~14: Consider inserting a comma here, unless the first half is essential to the meaning of the sentence.
Context: ...out how to query the database. With the schema you can then associate entities with mo...

(WITH_THAT_COMMA)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2738f67 and b5af0c7.

📒 Files selected for processing (3)
  • crates/torii/server/src/handlers/mcp.rs (5 hunks)
  • crates/torii/server/src/handlers/sql.rs (2 hunks)
  • crates/torii/server/static/mcp-instructions.txt (1 hunks)
🧰 Additional context used
🪛 LanguageTool
crates/torii/server/static/mcp-instructions.txt

[duplication] ~7-~7: Possible typo: you repeated a word
Context: ...te - dynamic model tables: Stores model data data associated with entities - models: Cont...

(ENGLISH_WORD_REPEAT_RULE)


[formatting] ~14-~14: Consider inserting a comma here, unless the first half is essential to the meaning of the sentence.
Context: ...out how to query the database. With the schema you can then associate entities with mo...

(WITH_THAT_COMMA)

🔇 Additional comments (1)
crates/torii/server/src/handlers/sql.rs (1)

119-158: Solid Implementation of map_row_to_json Function

Ohayo sensei! The new map_row_to_json function provides a comprehensive and efficient way to convert SQL rows to JSON values. It thoughtfully handles various data types, including TEXT, INTEGER, REAL, and BLOB, enhancing code modularity and reusability.

Comment on lines +297 to +301
if let Some(query) = params.get("arguments").and_then(Value::as_str) {
match sqlx::query(query).fetch_all(&*self.pool).await {
Ok(rows) => {
// Convert rows to JSON using the same logic as SqlHandler
let result = rows
.iter()
.map(|row| {
let mut obj = serde_json::Map::new();
for (i, column) in row.columns().iter().enumerate() {
let value: serde_json::Value = match column.type_info().name() {
"TEXT" => row.get::<Option<String>, _>(i).map_or(
serde_json::Value::Null,
serde_json::Value::String,
),
"INTEGER" => row
.get::<Option<i64>, _>(i)
.map_or(serde_json::Value::Null, |n| {
serde_json::Value::Number(n.into())
}),
"REAL" => row.get::<Option<f64>, _>(i).map_or(
serde_json::Value::Null,
|f| {
serde_json::Number::from_f64(f).map_or(
serde_json::Value::Null,
serde_json::Value::Number,
)
},
),
"BLOB" => row.get::<Option<Vec<u8>>, _>(i).map_or(
serde_json::Value::Null,
|bytes| {
serde_json::Value::String(STANDARD.encode(bytes))
},
),
_ => {
// Try different types in order
if let Ok(val) = row.try_get::<i64, _>(i) {
serde_json::Value::Number(val.into())
} else if let Ok(val) = row.try_get::<f64, _>(i) {
// Handle floating point numbers
serde_json::json!(val)
} else if let Ok(val) = row.try_get::<bool, _>(i) {
serde_json::Value::Bool(val)
} else if let Ok(val) = row.try_get::<String, _>(i) {
serde_json::Value::String(val)
} else {
// Handle or fallback to BLOB as base64
let val = row.get::<Option<Vec<u8>>, _>(i);
val.map_or(serde_json::Value::Null, |bytes| {
serde_json::Value::String(
STANDARD.encode(bytes),
)
})
}
}
};
obj.insert(column.name().to_string(), value);
}
Value::Object(obj)
})
.collect::<Vec<_>>();
// Convert rows to JSON using shared mapping function
let result = rows.iter().map(map_row_to_json).collect::<Vec<_>>();
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential Inconsistency in Parameter Handling in handle_query_tool

Ohayo sensei! In the handle_query_tool method, the code is attempting to extract the query parameter as a string directly from params.get("arguments"):

if let Some(query) = params.get("arguments").and_then(Value::as_str) {
    // Proceed with query execution
}

However, according to the inputSchema defined in the handle_tools_list method (lines 128-142), the arguments should be an object containing the query field. To ensure consistency and proper parameter extraction, consider modifying the code to:

if let Some(query) = params.get("arguments").and_then(|args| args.get("query")).and_then(Value::as_str) {
    // Proceed with query execution
}

This adjustment aligns with the defined schema and ensures the query parameter is correctly retrieved.

Copy link

codecov bot commented Dec 10, 2024

Codecov Report

Attention: Patch coverage is 0% with 127 lines in your changes missing coverage. Please review.

Project coverage is 55.72%. Comparing base (3e062fd) to head (b5af0c7).
Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/server/src/handlers/mcp.rs 0.00% 94 Missing ⚠️
crates/torii/server/src/handlers/sql.rs 0.00% 33 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2790      +/-   ##
==========================================
+ Coverage   55.58%   55.72%   +0.13%     
==========================================
  Files         436      436              
  Lines       55521    55384     -137     
==========================================
+ Hits        30862    30863       +1     
+ Misses      24659    24521     -138     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Nice cleanup.

@glihm glihm changed the title chore(torii-server): mcp and sql cleanup with instructions static file refactor(torii-server): mcp and sql cleanup with instructions static file Dec 10, 2024
@glihm glihm merged commit bcd581e into dojoengine:main Dec 10, 2024
13 of 14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants