Skip to content

initial commit for MCP server in OpenSearch #3781

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 10 commits into from
Apr 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

package org.opensearch.ml.common.transport.mcpserver.action;

import org.opensearch.action.ActionType;
import org.opensearch.ml.common.transport.mcpserver.responses.register.MLMcpRegisterNodesResponse;

public class MLMcpToolsRegisterOnNodesAction extends ActionType<MLMcpRegisterNodesResponse> {
public static MLMcpToolsRegisterOnNodesAction INSTANCE = new MLMcpToolsRegisterOnNodesAction();
public static final String NAME = "cluster:admin/opensearch/ml/mcp_tools/register_on_nodes";
Copy link
Collaborator

Choose a reason for hiding this comment

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

The name register_on_nodes is confusing, are we going to register tool on each data node ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes, every data node will be registered with mcp tools.

Copy link
Collaborator

Choose a reason for hiding this comment

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

@zane-neo Thanks for confirming. I have some concerns about registering MCP tools on each data node:

  • Consistency challenges: If multiple users try to register tools simultaneously, we could end up with inconsistent tool registrations across nodes (e.g., node 1 has user A's tool while node 2 has user B's tool). How do we maintain consistency?

  • Race conditions: What happens if tool registration requests conflict across nodes? We need a mechanism to handle concurrent registrations.

  • Synchronization overhead: Keeping tool registrations in sync across all data nodes adds complexity and network overhead.

  • Failure handling: How do we handle cases where tool registration succeeds on some nodes but fails on others? We need a robust rollback mechanism.

What are your thoughts on handling these concerns?

I would highly suggest considering this option #3781 (comment)

Is it possible to register all of these built-in tools by default ?


private MLMcpToolsRegisterOnNodesAction() {
super(NAME, MLMcpRegisterNodesResponse::new);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

package org.opensearch.ml.common.transport.mcpserver.action;

import org.opensearch.action.ActionType;
import org.opensearch.ml.common.transport.mcpserver.responses.remove.MLMcpRemoveNodesResponse;

public class MLMcpToolsRemoveOnNodesAction extends ActionType<MLMcpRemoveNodesResponse> {
public static MLMcpToolsRemoveOnNodesAction INSTANCE = new MLMcpToolsRemoveOnNodesAction();
public static final String NAME = "cluster:admin/opensearch/ml/mcp_tools/remove_on_nodes";

private MLMcpToolsRemoveOnNodesAction() {
super(NAME, MLMcpRemoveNodesResponse::new);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

package org.opensearch.ml.common.transport.mcpserver.requests.register;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;

import org.opensearch.action.ActionRequest;
import org.opensearch.action.ActionRequestValidationException;
import org.opensearch.core.common.io.stream.InputStreamStreamInput;
import org.opensearch.core.common.io.stream.OutputStreamStreamOutput;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.transport.TransportRequest;

import lombok.Builder;
import lombok.Data;

@Data
public class MLMcpToolsRegisterNodeRequest extends ActionRequest {
private McpTools mcpTools;

public MLMcpToolsRegisterNodeRequest(StreamInput in) throws IOException {
super(in);
this.mcpTools = new McpTools(in);
}

@Override
public ActionRequestValidationException validate() {
return null;
}

@Builder
public MLMcpToolsRegisterNodeRequest(McpTools mcpTools) {
this.mcpTools = mcpTools;
}

@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
mcpTools.writeTo(out);
}

public static MLMcpToolsRegisterNodeRequest fromActionRequest(TransportRequest actionRequest) {
Copy link
Contributor

Choose a reason for hiding this comment

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

We are using ActionRequest in place of TransportRequest in other parts of the code, is there a reason behind using raw TransportRequest

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I think both are fine as they're all in OpenSearch core so the code won't have runtime issue, I believe I copied from other files this.

if (actionRequest instanceof MLMcpToolsRegisterNodeRequest) {
return (MLMcpToolsRegisterNodeRequest) actionRequest;
}

try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamStreamOutput osso = new OutputStreamStreamOutput(baos)) {
actionRequest.writeTo(osso);
try (StreamInput input = new InputStreamStreamInput(new ByteArrayInputStream(baos.toByteArray()))) {
return new MLMcpToolsRegisterNodeRequest(input);
}
} catch (IOException e) {
throw new UncheckedIOException("Failed to parse ActionRequest into MLMcpToolsRegisterNodeRequest", e);
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package org.opensearch.ml.common.transport.mcpserver.requests.register;
Copy link
Contributor

@rithin-pullela-aws rithin-pullela-aws Apr 28, 2025

Choose a reason for hiding this comment

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

Add license header


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;

import org.opensearch.action.ActionRequest;
import org.opensearch.action.ActionRequestValidationException;
import org.opensearch.action.support.nodes.BaseNodesRequest;
import org.opensearch.core.common.io.stream.InputStreamStreamInput;
import org.opensearch.core.common.io.stream.OutputStreamStreamOutput;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.util.CollectionUtils;

import lombok.Data;

@Data
public class MLMcpToolsRegisterNodesRequest extends BaseNodesRequest<MLMcpToolsRegisterNodesRequest> {
private McpTools mcpTools;

public MLMcpToolsRegisterNodesRequest(StreamInput in) throws IOException {
super(in);
this.mcpTools = new McpTools(in);
}

public MLMcpToolsRegisterNodesRequest(String[] nodeIds, McpTools mcpTools) {
super(nodeIds);
this.mcpTools = mcpTools;
}

public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
mcpTools.writeTo(out);
}

@Override
public ActionRequestValidationException validate() {
if (CollectionUtils.isEmpty(mcpTools.getTools())) {
ActionRequestValidationException exception = new ActionRequestValidationException();
exception.addValidationError("tools list can not be null");
return exception;
}
return null;
}

public static MLMcpToolsRegisterNodesRequest fromActionRequest(ActionRequest actionRequest) {
if (actionRequest instanceof MLMcpToolsRegisterNodesRequest) {
return (MLMcpToolsRegisterNodesRequest) actionRequest;
}

try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamStreamOutput osso = new OutputStreamStreamOutput(baos)) {
actionRequest.writeTo(osso);
try (StreamInput input = new InputStreamStreamInput(new ByteArrayInputStream(baos.toByteArray()))) {
return new MLMcpToolsRegisterNodesRequest(input);
}
} catch (IOException e) {
throw new UncheckedIOException("Failed to parse ActionRequest into MLMcpToolsRegisterRequest", e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/*
*
* * Copyright OpenSearch Contributors
* * SPDX-License-Identifier: Apache-2.0
*
*/

package org.opensearch.ml.common.transport.mcpserver.requests.register;

import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken;

import java.io.IOException;
import java.util.Map;

import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;

import lombok.Data;
import lombok.extern.log4j.Log4j2;

/**
* This class represents a tool that can be registered with OpenSearch. It contains information about the tool's name,
* description, parameters, and schema.
*/
@Log4j2
@Data
public class McpTool implements ToXContentObject, Writeable {
private static final String NAME_FIELD = "name";
private static final String DESCRIPTION_FIELD = "description";
private static final String PARAMS_FIELD = "params";
Copy link
Collaborator

Choose a reason for hiding this comment

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

Let's use parameters to keep consistent with current design ?

Refer to this example of current tool definition

        {
            "type": "MLModelTool",
            "description": "A general tool to answer any question",
            "parameters": {
                "model_id": "your_llm_model_id",
                "prompt": "\n\nHuman:You are a professional data analysist. You will always answer question based on the given context first. If the answer is not directly shown in the context, you will analyze the data and find the answer. If you don't know the answer, just say don't know. \n\n Context:\n${parameters.PPLTool.output:-}\n\nHuman:${parameters.question}\n\nAssistant:"
            }
        }

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Done

private static final String SCHEMA_FIELD = "schema";
private final String name;
Copy link
Collaborator

@ylwu-amzn ylwu-amzn Apr 28, 2025

Choose a reason for hiding this comment

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

This is only for name or the tool type ? Current Agent Framework supports name and type when defining tool. That's for supporting multiple custom tools with same type. For example, user can define two MLModelTools with different name because they are for different purpose, for exampmle

[
   {
      "type": "MLModelTool",
     "name": "summarize"
...
    },
   {
      "type": "MLModelTool",
      "name": "translate"
...
    }
]

How about making this register MCP tool compatible with current tool definition ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Will change this in next PR.

private final String description;
private Map<String, Object> params;
private Map<String, Object> schema;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggest keep consistent with current tool definition, for example

    {
      "type": "IndexMappingTool",
      "attributes": {
        "input_schema": {
          "type": "object",
          "properties": {
            "index": {
              "type": "array",
              "description": "OpenSearch index name list, separated by comma. for example: index1, index2",
              "items": {
                "type": "string"
              }
            }
          },
          "required": ["index"],
          "additionalProperties": false
        },
        "strict": true
      }
    }

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Done

private static final String nameNotShownExceptionMessage = "name field required";

public McpTool(StreamInput streamInput) throws IOException {
name = streamInput.readString();
if (name == null) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is it possible that name is null? I see you already checked name == null in line 58

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Removed.

throw new IllegalArgumentException(nameNotShownExceptionMessage);
}
description = streamInput.readOptionalString();
if (streamInput.readBoolean()) {
params = streamInput.readMap(StreamInput::readString, StreamInput::readGenericValue);
}
if (streamInput.readBoolean()) {
schema = streamInput.readMap(StreamInput::readString, StreamInput::readGenericValue);
}
}

public McpTool(String name, String description, Map<String, Object> params, Map<String, Object> schema) {
if (name == null) {
throw new IllegalArgumentException(nameNotShownExceptionMessage);
}
this.name = name;
this.description = description;
this.params = params;
this.schema = schema;
}

public static McpTool parse(XContentParser parser) throws IOException {
String name = null;
String description = null;
Map<String, Object> params = null;
Map<String, Object> schema = null;
ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser);
while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
String fieldName = parser.currentName();
parser.nextToken();

switch (fieldName) {
case NAME_FIELD:
name = parser.text();
break;
case DESCRIPTION_FIELD:
description = parser.text();
break;
case PARAMS_FIELD:
params = parser.map();
break;
case SCHEMA_FIELD:
schema = parser.map();
break;
default:
parser.skipChildren();
break;
}
}
if (name == null) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

As line 58 already checked null name, we can skip checking here

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Done

throw new IllegalArgumentException(nameNotShownExceptionMessage);
}
return new McpTool(name, description, params, schema);
}

@Override
public void writeTo(StreamOutput streamOutput) throws IOException {
streamOutput.writeString(name);
streamOutput.writeOptionalString(description);
if (params != null) {
streamOutput.writeBoolean(true);
streamOutput.writeMap(params, StreamOutput::writeString, StreamOutput::writeGenericValue);
} else {
streamOutput.writeBoolean(false);
}

if (schema != null) {
streamOutput.writeBoolean(true);
streamOutput.writeMap(schema, StreamOutput::writeString, StreamOutput::writeGenericValue);
} else {
streamOutput.writeBoolean(false);
}
}

@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params xcontentParams) throws IOException {
builder.startObject();
builder.field(NAME_FIELD, name);
if (description != null) {
builder.field(DESCRIPTION_FIELD, description);
}
if (params != null && !params.isEmpty()) {
builder.field(PARAMS_FIELD, params);
}
if (schema != null && !schema.isEmpty()) {
builder.field(SCHEMA_FIELD, schema);
}
builder.endObject();
return builder;
}
}
Loading
Loading