diff --git a/.classpath b/.classpath index e7c4f49ac2055aac6978f0bd949528595cff19cd..3261bfe9bff699cbff09a1c18b2d79dd3e735ee5 100644 --- a/.classpath +++ b/.classpath @@ -1,37 +1,50 @@ - + + + + + + + + - + + - + - - + - + + + + + + - + - + - + - + - + + diff --git a/.project b/.project index ec91655dce6f23bb621faebfc80549036fb2499c..7ae1829f99830031a51ebcc8c32d75f0064e5386 100644 --- a/.project +++ b/.project @@ -20,4 +20,15 @@ org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature + + + 1747415794116 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs index 29abf999564110a0d6aca109f55f439c72b7031c..742ce1f0065ae0f4cd57127a673e1acdb7df7a56 100644 --- a/.settings/org.eclipse.core.resources.prefs +++ b/.settings/org.eclipse.core.resources.prefs @@ -1,6 +1,6 @@ eclipse.preferences.version=1 -encoding//src/main/java=UTF-8 +encoding//src/main/java=utf-8 encoding//src/main/resources=UTF-8 -encoding//src/test/java=UTF-8 +encoding//src/test/java=utf-8 encoding//src/test/resources=UTF-8 encoding/=UTF-8 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs index 3328195d65370652055cb326fd9d76eb1bee1841..1c94aa9cfd6dfa7ebb0dde47da29b3e4bf88f2f1 100644 --- a/.settings/org.eclipse.jdt.core.prefs +++ b/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,9 @@ eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore +org.eclipse.jdt.core.compiler.annotation.nonnull=org.springframework.lang.NonNull +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.springframework.lang.NonNullApi +org.eclipse.jdt.core.compiler.annotation.nullable=org.springframework.lang.Nullable +org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.methodParameters=generate org.eclipse.jdt.core.compiler.codegen.targetPlatform=17 @@ -11,6 +16,13 @@ org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=warning +org.eclipse.jdt.core.compiler.problem.nullReference=warning +org.eclipse.jdt.core.compiler.problem.nullSpecViolation=warning +org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=ignore +org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning -org.eclipse.jdt.core.compiler.release=enabled +org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=enabled +org.eclipse.jdt.core.compiler.processAnnotations=enabled +org.eclipse.jdt.core.compiler.release=disabled org.eclipse.jdt.core.compiler.source=17 diff --git a/Dockerfile b/Dockerfile index 0767d5782e2b836774b53e55734470bfa21cccc5..4a700d82def91f083ba0b23dfac7dfd3f61dd2cd 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,6 +3,6 @@ MAINTAINER osl.etsi.org RUN mkdir /opt/osl -COPY target/org.etsi.osl.mcp.server-1.0.0-exec.jar /opt/osl -CMD ["java", "-jar", "/opt/osl/org.etsi.osl.mcp.server-1.0.0-exec.jar"] +COPY target/org.etsi.osl.mcp.server-1.1.0-exec.jar /opt/osl +CMD ["java", "-jar", "/opt/osl/org.etsi.osl.mcp.server-1.1.0-exec.jar"] diff --git a/README.md b/README.md index f31bd0bace83a8c932eeacf0fc633af49d9e3566..76a4157600899bee658b0e0e8208b5dbbdb67898 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,152 @@ -# org.etsi.osl.mcp.server +# OpenSlice MCP Server +A Model Context Protocol (MCP) server that provides AI assistants with access to OpenSlice service management capabilities through standardized tools and resources. +## Overview -## Getting started +The OpenSlice MCP Server is a Spring Boot application that bridges OpenSlice's service catalog and management system with AI assistants like Claude via the Model Context Protocol. It exposes OpenSlice functionality as MCP tools, allowing AI assistants to interact with service catalogs, manage service orders, and retrieve service information. -To make it easy for you to get started with GitLab, here's a list of recommended next steps. +## What is OpenSlice? -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! +[OpenSlice](https://osl.etsi.org/) is an open-source platform for managing network services and resources based on TMForum standards. It provides service catalog management, service ordering, and service lifecycle management capabilities for telecommunications and cloud services. -## Add your files +## Features -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: +### MCP Tools Available -``` -cd existing_repo -git remote add origin https://labs.etsi.org/rep/osl/code/org.etsi.osl.mcp.server.git -git branch -M main -git push -uf origin main -``` +- **Service Catalog Management**: + - Browse service catalogs and categories + - Search for service specifications + - Get detailed service specification information + - Access resource specifications -## Integrate with your tools +- **Service Order Management**: + - Create service orders with customizable characteristics + - Track service order status and progress + - Retrieve service order details and history -- [ ] [Set up project integrations](https://labs.etsi.org/rep/osl/code/org.etsi.osl.mcp.server/-/settings/integrations) +- **Service Instance Management**: + - View service instances and their details + - Update service characteristics + - Monitor service status and supporting resources -## Collaborate with your team +- **Resource Management**: + - Access resource information and specifications + - Track resource status and characteristics -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) +### Authentication & Security -## Test and Deploy +- OAuth2/JWT token-based authentication +- Integration with Keycloak identity provider +- Secure communication with OpenSlice backend systems -Use the built-in continuous integration in GitLab. +## Architecture -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) +The server implements the MCP protocol using Spring AI's MCP server capabilities: -*** +- **Transport**: Server-Sent Events (SSE) for real-time communication +- **Message Queue**: Apache ActiveMQ for backend communication with OpenSlice +- **Protocol**: Model Context Protocol v1.0 for AI assistant integration -# Editing this README +## Configuration -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. +Key configuration options in `application.yaml`: -## Suggestions for a good README +```yaml +server: + port: 13015 -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. +spring: + ai: + mcp: + server: + name: org.etsi.osl.mcp.server + sse-message-endpoint: /mcp/messages + stdio: false + + activemq: + brokerUrl: tcp://portal.openslice.eu:61616 + + security: + oauth2: + resourceserver: + jwt: + issuer-uri: https://portal.openslice.eu/auth/realms/openslice +``` -## Name -Choose a self-explaining name for your project. +## Installation & Usage -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. +### Prerequisites -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. +- Java 17 or higher +- Maven 3.6+ +- Access to an OpenSlice deployment +- Access to the OpenSlice ActiveMQ message broker -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. +### Building -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. +```bash +mvn clean package +``` -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. +### Running -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. +```bash +java -jar target/org.etsi.osl.mcp.server-*.jar +``` + +The server will start on port 13015 and provide MCP endpoints for AI assistant integration. -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. +### Integration with Claude -## Contributing -State if you are open to contributions and what your requirements are for accepting them. +Once running, the server can be connected to Claude Code or other MCP-compatible clients: -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. +1. The server exposes its MCP interface at: `http://localhost:13015/mcp/messages` +2. AI assistants can discover and use the available tools for OpenSlice operations +3. Authentication is required via JWT tokens from the configured OAuth2 provider -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. +for Claude: + +``` + +{ + "mcpServers": { + + "oslserver": { + "command": "npx", + "args": [ + "mcp-remote@latest", + "http://portal.openslice.eu:13015/sse", + "--allow-http"] + } + + } +} +``` + +> Note: At the time of your download, the `mcp-remote@latest` tag may be incompatible with the committed OSL MCP Server, due to the growing ongoing research. If you experience connectivity issues with your MCP Client, please use `mcp-remote@0.1.18`, which is extensively tested and works. + +## Dependencies + +- Spring Boot 3.4.5 +- Spring AI with MCP server support +- Apache Camel for message routing +- TMForum API models for telecommunications standards +- ActiveMQ for message queue communication ## License -For open source projects, say how it is licensed. -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +This project is licensed under the Apache License 2.0. + +## Related Projects + +- [OpenSlice](https://osl.etsi.org/) - The main OpenSlice platform +- [Model Context Protocol](https://modelcontextprotocol.io/) - Protocol specification for AI assistant integrations + +## Support + +For issues and questions: +- See the published demonstration: https://www.youtube.com/watch?v=fSDDQvdbuME +- OpenSlice documentation: https://osl.etsi.org/documentation +- ETSI OSL GitLab: https://labs.etsi.org/rep/osl/ \ No newline at end of file diff --git a/pom.xml b/pom.xml index a5a1572a083f677f8df4ff5b265c400a22d9d96b..5643e4326094c39379b21add819ca0e2185a8b12 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ org.etsi.osl org.etsi.osl.main - 2025Q2 + 2025Q4 ../org.etsi.osl.main @@ -26,7 +26,7 @@ UTF-8 UTF-8 3.4.5 - 1.0.0-M7 + 1.1.0 1.18.28 2.1.0 1.5.3.Final @@ -98,15 +98,32 @@ org.springframework.ai - spring-ai-starter-mcp-server-webflux + spring-ai-starter-mcp-server-webmvc + + org.springaicommunity + mcp-server-security + 0.0.4 + + + org.springframework.boot + spring-boot-starter-security + + + + + org.springframework.boot + spring-boot-starter-oauth2-resource-server + - - + + com.jayway.jsonpath + json-path + org.projectlombok @@ -133,8 +150,6 @@ - - diff --git a/src/main/java/org/etsi/osl/mcp/server/OSLMCPServerApplication.java b/src/main/java/org/etsi/osl/mcp/server/OSLMCPServerApplication.java index 7d75775f85c92a514bd2f9ee82ed1b72f8303ff6..5808501beeefe89f9577585515e1ca2cb0aa785d 100644 --- a/src/main/java/org/etsi/osl/mcp/server/OSLMCPServerApplication.java +++ b/src/main/java/org/etsi/osl/mcp/server/OSLMCPServerApplication.java @@ -35,11 +35,11 @@ public class OSLMCPServerApplication { SpringApplication.run(OSLMCPServerApplication.class, args); } - @Bean - public ToolCallbackProvider serviceTools( ServiceCatalogTools oslServices) { - return MethodToolCallbackProvider.builder().toolObjects( oslServices ).build(); - } - +// @Bean +// public ToolCallbackProvider serviceTools( ServiceCatalogTools oslServices) { +// return MethodToolCallbackProvider.builder().toolObjects( oslServices ).build(); +// } +// @Bean diff --git a/src/main/java/org/etsi/osl/mcp/server/ProductCatalogTools.java b/src/main/java/org/etsi/osl/mcp/server/ProductCatalogTools.java index f47f1597ade0ed3ec23628835a282b5ea9d57a54..d3ae3208e062d5fbe5f6ff66f8f65dbaf4e0cfec 100644 --- a/src/main/java/org/etsi/osl/mcp/server/ProductCatalogTools.java +++ b/src/main/java/org/etsi/osl/mcp/server/ProductCatalogTools.java @@ -26,6 +26,8 @@ import org.etsi.osl.tmf.prm669.model.RelatedParty; import org.etsi.osl.tmf.ri639.model.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springaicommunity.mcp.annotation.McpTool; +import org.springaicommunity.mcp.context.McpSyncRequestContext; import org.springframework.ai.tool.annotation.Tool; import org.springframework.beans.factory.annotation.Autowired; @@ -167,17 +169,40 @@ public class ProductCatalogTools { } - @Tool(description = "Search for OSL product Offerings that are published and available for product ordering in all categories") - public JsonNode searchOSLProductOfferings( List searchStrings) { + @McpTool(description = "Search for OSL product Offerings that are published and available for product ordering in all categories") + public JsonNode searchOSLProductOfferings( + McpSyncRequestContext context,List searchStrings) { - logger.info("searchOSLProductOfferings containing workds: {}", searchStrings); + // Send logging notification + context.info("Processing data: " + searchStrings); + // Send progress notification (using convenient method) + context.progress(p -> p.progress(0.5).total(1.0).message("Processing...")); + logger.info("searchOSLServiceSpecifications containing words: {}", searchStrings); + + // Split strings that contain multiple words separated by comma or space + List expandedSearchStrings = new java.util.ArrayList<>(); + for (String searchString : searchStrings) { + if (searchString.contains(",") || searchString.contains(" ")) { + // Split by comma or space and add each word separately + String[] words = searchString.split("[,\\s]+"); + for (String word : words) { + String trimmedWord = word.trim(); + if (!trimmedWord.isEmpty()) { + expandedSearchStrings.add(trimmedWord); + } + } + } else { + expandedSearchStrings.add(searchString); + } + } + logger.info("Expanded search strings: {}", expandedSearchStrings); - List spec = aCatalogClient.searchProductOfferings( searchStrings ); + List spec = aCatalogClient.searchProductOfferings( expandedSearchStrings ); // Filter and get result as JSON string try { - String[] tokens = {"id", "name", "description", "isBundle", "@type", "configurable", "valueType", "isBundle" }; + String[] tokens = {"productOfferingId", "productName", "productDescription", "isBundle", "@type", "isBundle", "categoryName" }; JsonNode filtered = JsonMassage.filterJsonByTokens( spec, tokens); return filtered; } catch (Exception e) { diff --git a/src/main/java/org/etsi/osl/mcp/server/ServiceCatalogQClient.java b/src/main/java/org/etsi/osl/mcp/server/ServiceCatalogQClient.java index a9756afa7689eb68870245bd9929f8d63663ad80..a08fd4b11864c1281a5b337af0e288b0c579ae60 100644 --- a/src/main/java/org/etsi/osl/mcp/server/ServiceCatalogQClient.java +++ b/src/main/java/org/etsi/osl/mcp/server/ServiceCatalogQClient.java @@ -107,7 +107,7 @@ public class ServiceCatalogQClient extends RouteBuilder { * @throws IOException */ public ServiceSpecification retrieveServiceSpec(String specid) { - logger.info("will retrieve Service Specification from catalog orderid=" + specid ); + logger.info("will retrieve Service Specification from catalog specid=" + specid ); try { Object response = template. diff --git a/src/main/java/org/etsi/osl/mcp/server/ServiceCatalogTools.java b/src/main/java/org/etsi/osl/mcp/server/ServiceCatalogTools.java index 365fb6b54b7263769d48ab95ca93c06c99dde720..10b27d945f7092ba2193bda25c2f167166348c40 100644 --- a/src/main/java/org/etsi/osl/mcp/server/ServiceCatalogTools.java +++ b/src/main/java/org/etsi/osl/mcp/server/ServiceCatalogTools.java @@ -2,14 +2,8 @@ package org.etsi.osl.mcp.server; import java.io.IOException; import java.time.OffsetDateTime; -import java.util.Arrays; -import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Set; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; import org.etsi.osl.tmf.common.model.Any; import org.etsi.osl.tmf.common.model.service.Characteristic; import org.etsi.osl.tmf.common.model.service.Note; @@ -17,10 +11,8 @@ import org.etsi.osl.tmf.common.model.service.ServiceSpecificationRef; import org.etsi.osl.tmf.prm669.model.RelatedParty; import org.etsi.osl.tmf.rcm634.model.LogicalResourceSpecification; import org.etsi.osl.tmf.ri639.model.Resource; -import org.etsi.osl.tmf.scm633.model.ServiceCandidate; import org.etsi.osl.tmf.scm633.model.ServiceCatalog; import org.etsi.osl.tmf.scm633.model.ServiceCategory; -import org.etsi.osl.tmf.scm633.model.ServiceCategoryRef; import org.etsi.osl.tmf.scm633.model.ServiceSpecification; import org.etsi.osl.tmf.sim638.model.Service; import org.etsi.osl.tmf.sim638.model.ServiceUpdate; @@ -31,12 +23,14 @@ import org.etsi.osl.tmf.so641.model.ServiceOrderStateType; import org.etsi.osl.tmf.so641.model.ServiceRestriction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.ai.tool.annotation.Tool; +import org.springaicommunity.mcp.annotation.McpTool; +import org.springaicommunity.mcp.annotation.McpToolParam; +import org.springaicommunity.mcp.context.McpSyncRequestContext; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.web.client.RestClient; -import jakarta.validation.Valid; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.context.SecurityContextHolder; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; /** * @@ -55,14 +49,24 @@ public class ServiceCatalogTools { ServiceCatalogQClient aCatalogClient; - @Tool(description = "Get a list of all published OSL OpenSlice service catalogs." +// @McpTool(description="Get your name") +// public String getYourName(ToolContext context) { +// logger.info("ToolContext: {}", McpRequestHolder.get(context).headers()); +// return SecurityContextHolder.getContext().getAuthentication().getName(); +// } + + + @McpTool (description = "Get a list of all published OSL OpenSlice service catalogs." + "Each catalog contains service categories, that we can search individually to get the details and contents of each category.") public JsonNode getOSLServiceCatalogs() { logger.info("getOSLServiceCatalogs"); List serviceCatalogs = aCatalogClient.retrieveServiceCatalogs(); - + var authentication = SecurityContextHolder.getContext().getAuthentication(); + var name = authentication.getName(); + + logger.info("getOSLServiceCatalogs {}", name); // Filter and get result as JSON string try { @@ -80,8 +84,8 @@ public class ServiceCatalogTools { } - @Tool(description = "Get OSL categories in catalog providing a catalog name") - public JsonNode getOSLServiceCategories(String catalogName) { + @McpTool(description = "Get OSL categories in catalog providing a catalog name") + public JsonNode getOSLServiceCategories(@McpToolParam(description = "The service catalog name", required = true) String catalogName) { logger.info("getOSLServiceCategories {}", catalogName); @@ -104,8 +108,8 @@ public class ServiceCatalogTools { } - @Tool(description = "Get a list of OSL service specification references in a service category, given a category ID") - public JsonNode getOSLServiceSpecsInCategory(String categoryId) { + @McpTool(description = "Get a list of OSL service specification references in a service category, given a category ID") + public JsonNode getOSLServiceSpecsInCategory(@McpToolParam(description = "The categoryId needed to search service specification references", required = true) String categoryId) { logger.info("getOSLServiceSpecsInCategory {}", categoryId); @@ -132,8 +136,9 @@ public class ServiceCatalogTools { } - @Tool(description = "Get all the details of an OSL service specification given a service Specification Id") - public JsonNode getOSLServiceSpecificationByServiceSpecificationId(String serviceSpecId) { + @McpTool(description = "Get all the details of an OSL service specification given a service Specification Id") + public JsonNode getOSLServiceSpecificationByServiceSpecificationId( + @McpToolParam(description = "The service Specification Id needed to get service specification details", required = true) String serviceSpecId) { logger.info("getOSLServiceByServiceSpecificationId {}", serviceSpecId); @@ -157,8 +162,9 @@ public class ServiceCatalogTools { - @Tool(description = "Get all the details of an OSL resource specification given a resource Specification Id") - public JsonNode getOSLResourceSpecificationByResourceSpecificationId(String resourceSpecId) { + @McpTool(description = "Get all the details of an OSL resource specification given a resource Specification Id") + public JsonNode getOSLResourceSpecificationByResourceSpecificationId( + @McpToolParam(description = "The resource Specification Id needed to get resource specification details", required = true) String resourceSpecId) { logger.info("getOSLResourceSpecificationByResourceSpecificationId {}", resourceSpecId); @@ -181,17 +187,44 @@ public class ServiceCatalogTools { - @Tool(description = "Search for OSL service specifications that are published and available for service ordering in all categories") - public JsonNode searchOSLServiceSpecifications( List searchStrings) { - + @McpTool(description = "Search for OSL service specifications that are published and available for service ordering in all categories") + public JsonNode searchOSLServiceSpecifications( + McpSyncRequestContext context, + @McpToolParam(description = "A list of search strings", required = true) List searchStrings) { + + // Send logging notification + context.info("Processing data: " + searchStrings); + // Send progress notification (using convenient method) + context.progress(p -> p.progress(0.5).total(1.0).message("Processing...")); logger.info("searchOSLServiceSpecifications containing words: {}", searchStrings); - List spec = aCatalogClient.searchServiceSpecs( searchStrings ); + // Split strings that contain multiple words separated by comma or space + List expandedSearchStrings = new java.util.ArrayList<>(); + for (String searchString : searchStrings) { + if (searchString.contains(",") || searchString.contains(" ")) { + // Split by comma or space and add each word separately + String[] words = searchString.split("[,\\s]+"); + for (String word : words) { + String trimmedWord = word.trim(); + if (!trimmedWord.isEmpty()) { + expandedSearchStrings.add(trimmedWord); + } + } + } else { + expandedSearchStrings.add(searchString); + } + } + logger.info("Expanded search strings: {}", expandedSearchStrings); + List spec = aCatalogClient.searchServiceSpecs( expandedSearchStrings ); + + // Ping the client + context.ping(); + // Filter and get result as JSON string try { - String[] tokens = {"id", "name", "description", "@type", "configurable", "valueType", "isBundle" }; + String[] tokens = {"serviceSpecificationId", "serviceName", "serviceDescription", "@type", "isBundle", "categoryName" }; JsonNode filtered = JsonMassage.filterJsonByTokens( spec, tokens); return filtered; } catch (Exception e) { @@ -204,12 +237,20 @@ public class ServiceCatalogTools { return rootNode; } - @Tool(description = "Create a service order given a Service Specification id, the Start date an end date of the order. " + @PreAuthorize("isAuthenticated()") + @McpTool(description = "Create a service order given a Service Specification id, the Start date an end date of the order. " + "The user can provide also characteristics of service in the map with format key, value" + "Date Time has the format YYYY-MM-DDTHH:mm:ss+00:00") - public String createServiceOrder(String serviceSpecId, String startDate, String endDate, Map characteristics) { + public String createServiceOrder( + @McpToolParam(description = "The Service Specification id", required = true) String serviceSpecId, + @McpToolParam(description = "The start date", required = true) String startDate, + @McpToolParam(description = "Then end date", required = true) String endDate, + @McpToolParam(description = "A list of characteristics, key=characteristic name, value=characterisitc value", required = true) Map characteristics) { + + var authentication = SecurityContextHolder.getContext().getAuthentication(); + var username = authentication.getName(); - logger.info("createServiceOrder {} {} {} {}", serviceSpecId, startDate, endDate, characteristics.toString()); + logger.info("createServiceOrder {} {} {} {} {}", username, serviceSpecId, startDate, endDate, characteristics.toString()); ServiceOrderCreate sonew = new ServiceOrderCreate(); @@ -235,16 +276,14 @@ public class ServiceCatalogTools { if (sonew.getRelatedParty() == null) { RelatedParty rp = new RelatedParty(); - rp.setName("MCP"); + rp.setName(username); rp.setRole("REQUESTER"); sonew.addRelatedPartyItem(rp); } if (sonew.getNote() == null) { Note n = new Note(); - - n.setText( "Order created by MCP"); - + n.setText( "Order created by MCP for user: " + username); sonew.addNoteItem(n); } @@ -286,12 +325,13 @@ public class ServiceCatalogTools { } - @Tool(description = "Provide details for a service order given a Service Order id. " + @McpTool(description = "Provide details for a service order given a Service Order id. " + "Focus attention to:" + "- the state of the service order" + "- and each order item. Especially for each order item focus to the service and especially: status, characteristics and supporting services." + "- For each supporting service we can retrieve more information by using the service id.") - public JsonNode getServiceOrder(String serviceOrderId) { + public JsonNode getServiceOrder( + @McpToolParam(description = "The Service Order id", required = true) String serviceOrderId) { logger.info("serviceOrderId {} {} {} {}", serviceOrderId); ServiceOrder so = aCatalogClient.retrieveServiceOrder(serviceOrderId); @@ -315,10 +355,10 @@ public class ServiceCatalogTools { } - @Tool(description = "Provide details for a service given a Service id. Especially for name, state, characteristics, supporting Services and supporting Resources." + @McpTool(description = "Provide details for a service given a Service id. Especially for name, state, characteristics, supporting Services and supporting Resources." + "We can get details for each supporting service using the service id." + "and for each supporting resource using the resource id.") - public JsonNode getService(String serviceId) { + public JsonNode getService(@McpToolParam(description = "The Service id", required = true) String serviceId) { logger.info("getService {} {} {} {}", serviceId); Service s = aCatalogClient.retrieveService(serviceId); // Filter and get result as JSON string @@ -339,9 +379,9 @@ public class ServiceCatalogTools { } - @Tool(description = "Provide details for a resource given a Resourceid. Especially for name, status, characteristics." + @McpTool(description = "Provide details for a resource given a Resourceid. Especially for name, status, characteristics." + "We can get details for each supporting resource using the resource id.") - public JsonNode getResource(String resourceId) { + public JsonNode getResource(@McpToolParam(description = "The Resource id", required = true) String resourceId) { logger.info("getResource {} {} {} {}", resourceId); Resource r = aCatalogClient.retrieveResource ( resourceId); // Filter and get result as JSON string @@ -362,9 +402,11 @@ public class ServiceCatalogTools { } - @Tool(description = "Update and change a service given a Service id." + @McpTool(description = "Update and change a service given a Service id." + "We provide also characteristics of service in the map with format key, value") - public String updateService(String serviceId, Map characteristics) { + public String updateService( + @McpToolParam(description = "The Service id", required = true) String serviceId, + @McpToolParam(description = "A list of characteristics, key=characteristic name, value=characterisitc value", required = true) Map characteristics) { logger.info("updateService {} {} {} {}", serviceId); ServiceUpdate su = new ServiceUpdate(); diff --git a/src/main/java/org/etsi/osl/mcp/server/WebSecurityConfigKeycloak.java b/src/main/java/org/etsi/osl/mcp/server/WebSecurityConfigKeycloak.java new file mode 100644 index 0000000000000000000000000000000000000000..58655535680ce1ae3ffa4bbd4fec6f8dc5f96ac6 --- /dev/null +++ b/src/main/java/org/etsi/osl/mcp/server/WebSecurityConfigKeycloak.java @@ -0,0 +1,335 @@ +package org.etsi.osl.mcp.server; + +import java.net.URL; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import com.jayway.jsonpath.JsonPath; +import com.jayway.jsonpath.PathNotFoundException; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.web.ServerProperties; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.NestedConfigurationProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.core.convert.converter.Converter; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.security.authentication.AbstractAuthenticationToken; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.AuthenticationManagerResolver; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.oauth2.jwt.Jwt; +import org.springframework.security.oauth2.jwt.JwtClaimNames; +import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.jwt.JwtDecoders; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken; +import org.springframework.security.oauth2.server.resource.authentication.JwtIssuerAuthenticationManagerResolver; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.stereotype.Component; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +import jakarta.servlet.http.HttpServletRequest; +import lombok.Data; +import lombok.RequiredArgsConstructor; + +@Configuration +@EnableWebSecurity +@EnableMethodSecurity +@Profile("!testing") +public class WebSecurityConfigKeycloak { + + @Bean + SecurityFilterChain filterChain(HttpSecurity http, ServerProperties serverProperties, + @Value("${origins:[]}") String[] origins, @Value("${permit-all:[]}") String[] permitAll, + AuthenticationManagerResolver authenticationManagerResolver) throws Exception { + + http.oauth2ResourceServer(oauth2 -> oauth2.authenticationManagerResolver(authenticationManagerResolver)); + + // Enable and configure CORS + http.cors(cors -> cors.configurationSource(corsConfigurationSource(origins))); + + // State-less session (state in access-token only) + http.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); + + // Disable CSRF because of state-less session-management + http.csrf(csrf -> csrf.disable()); + + // Return 401 (unauthorized) instead of 302 (redirect to login) when + // authorization is missing or invalid + http.exceptionHandling(eh -> eh.authenticationEntryPoint((request, response, authException) -> { + response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Restricted Content\""); + response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase()); + })); + + // If SSL enabled, disable http (https only) + if (serverProperties.getSsl() != null && serverProperties.getSsl().isEnabled()) { + http.requiresChannel(channel -> channel.anyRequest().requiresSecure()); + } + + // @formatter:off + http.authorizeHttpRequests(requests -> requests + //.requestMatchers(permitAll).permitAll() + .anyRequest().permitAll()); + // @formatter:on + + return http.build(); + } + + private UrlBasedCorsConfigurationSource corsConfigurationSource(String[] origins) { + final var configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(Arrays.asList(origins)); + configuration.setAllowedMethods(List.of("*")); + configuration.setAllowedHeaders(List.of("*")); + configuration.setExposedHeaders(List.of("*")); + configuration.setAllowCredentials(true); + + final var source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", configuration); + return source; + } + + @Data + @Configuration + @ConfigurationProperties(prefix = "spring-addons") + static class SpringAddonsProperties { + private IssuerProperties[] issuers = {}; + + @Data + static class IssuerProperties { + private URL uri; + + @NestedConfigurationProperty + private ClaimMappingProperties[] claims; + + private String usernameJsonPath = JwtClaimNames.SUB; + + @Data + static class ClaimMappingProperties { + private String jsonPath; + private CaseProcessing caseProcessing = CaseProcessing.UNCHANGED; + private String prefix = ""; + + static enum CaseProcessing { + UNCHANGED, TO_LOWER, TO_UPPER + } + } + } + + public IssuerProperties get(URL issuerUri) throws MisconfigurationException { + final var issuerProperties = Stream.of(issuers).filter(iss -> issuerUri.toString().equals(iss.getUri().toString())).toList(); + if (issuerProperties.size() == 0) { + throw new MisconfigurationException( + "Missing authorities mapping properties for %s".formatted(issuerUri.toString())); + } + if (issuerProperties.size() > 1) { + throw new MisconfigurationException( + "Too many authorities mapping properties for %s".formatted(issuerUri.toString())); + } + return issuerProperties.get(0); + } + + static class MisconfigurationException extends RuntimeException { + private static final long serialVersionUID = 5887967904749547431L; + + public MisconfigurationException(String msg) { + super(msg); + } + } + } + + @RequiredArgsConstructor + static class JwtGrantedAuthoritiesConverter implements Converter> { + private final SpringAddonsProperties.IssuerProperties properties; + + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + public Collection convert(Jwt jwt) { + + + return Stream.of(properties.claims).flatMap(claimProperties -> { + Object claim; + try { + claim = JsonPath.read(jwt.getClaims(), claimProperties.jsonPath); + } catch (PathNotFoundException e) { + claim = null; + } + if (claim == null) { + return Stream.empty(); + } + if (claim instanceof String claimStr) { + return Stream.of(claimStr.split(",")); + } + if (claim instanceof String[] claimArr) { + return Stream.of(claimArr); + } + if (Collection.class.isAssignableFrom(claim.getClass())) { + final var iter = ((Collection) claim).iterator(); + if (!iter.hasNext()) { + return Stream.empty(); + } + final var firstItem = iter.next(); + if (firstItem instanceof String) { + return (Stream) ((Collection) claim).stream(); + } + if (Collection.class.isAssignableFrom(firstItem.getClass())) { + return (Stream) ((Collection) claim).stream() + .flatMap(colItem -> ((Collection) colItem).stream()).map(String.class::cast); + } + } + return Stream.empty(); + }) /* Insert some transformation here if you want to add a prefix like "ROLE_" or force upper-case authorities */ + + .map(s -> "ROLE_" + s) + .map(SimpleGrantedAuthority::new) + .map(GrantedAuthority.class::cast).toList(); + } + } + + @Component + @RequiredArgsConstructor + static class SpringAddonsJwtAuthenticationConverter implements Converter { + private final SpringAddonsProperties springAddonsProperties; + + @Override + public AbstractAuthenticationToken convert(Jwt jwt) { + final var issuerProperties = springAddonsProperties.get(jwt.getIssuer()); + final var authorities = new JwtGrantedAuthoritiesConverter(issuerProperties).convert(jwt); + final String username = JsonPath.read(jwt.getClaims(), issuerProperties.getUsernameJsonPath()); + return new JwtAuthenticationToken(jwt, authorities, username); + } + } + + @Bean + AuthenticationManagerResolver authenticationManagerResolver( + SpringAddonsProperties addonsProperties, SpringAddonsJwtAuthenticationConverter authenticationConverter) { + final Map authenticationProviders = Stream.of(addonsProperties.getIssuers()) + .map(SpringAddonsProperties.IssuerProperties::getUri).map(URL::toString) + .collect(Collectors.toMap(issuer -> issuer, + issuer -> authenticationProvider(issuer, authenticationConverter)::authenticate)); + return new JwtIssuerAuthenticationManagerResolver( + (AuthenticationManagerResolver) authenticationProviders::get); + } + + JwtAuthenticationProvider authenticationProvider(String issuer, + SpringAddonsJwtAuthenticationConverter authenticationConverter) { + JwtDecoder decoder = JwtDecoders.fromIssuerLocation(issuer); + var provider = new JwtAuthenticationProvider(decoder); + provider.setJwtAuthenticationConverter(authenticationConverter); + return provider; + } +} + +//@Configuration +//@EnableWebSecurity +//@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class) +//@Profile("!testing") +//public class WebSecurityConfigKeycloak extends KeycloakWebSecurityConfigurerAdapter { +// +// +// +// @Autowired +// private RestAuthenticationEntryPoint restAuthenticationEntryPoint; +// +// @Autowired +// public void configureGlobal( +// AuthenticationManagerBuilder auth) throws Exception { +// +// KeycloakAuthenticationProvider keycloakAuthenticationProvider +// = keycloakAuthenticationProvider(); +// keycloakAuthenticationProvider.setGrantedAuthoritiesMapper( +// new SimpleAuthorityMapper()); +// auth.authenticationProvider(keycloakAuthenticationProvider); +// } +// +// @Bean +// public KeycloakSpringBootConfigResolver KeycloakConfigResolver() { +// return new KeycloakSpringBootConfigResolver(); +// } +// +// @Bean +// @Override +// protected SessionAuthenticationStrategy sessionAuthenticationStrategy() { +// return new RegisterSessionAuthenticationStrategy( +// new SessionRegistryImpl()); +// } +// +//// +//// @Override +//// @Bean("authenticationManager") +//// public AuthenticationManager authenticationManagerBean() throws Exception { +//// return super.authenticationManagerBean(); +//// } +// +// //see also https://www.baeldung.com/securing-a-restful-web-service-with-spring-security +// @Override +// protected void configure(final HttpSecurity http) throws Exception { +// // @formatter:off +// http.authorizeRequests() +//// .antMatchers("/sessions/**").permitAll() +//// .antMatchers("/register/**").permitAll() +//// //.antMatchers("/sessions/logout").permitAll() +//// .antMatchers("/categories/**").permitAll() +//// .antMatchers("/experiments/**").permitAll() +//// .antMatchers("/vxfs/**").permitAll() +//// .antMatchers("/login").permitAll() +//// .antMatchers("/images/**").permitAll() +//// .antMatchers("/packages/**").permitAll() +//// .antMatchers("/testweb/**").permitAll() +//// .antMatchers("/oauth/token/revokeById/**").permitAll() +//// .antMatchers("/tokens/**").permitAll() +//// .antMatchers("/actuator/**").permitAll() +//// .antMatchers("/swagger/**").permitAll() +//// .antMatchers("/v2/**").permitAll() +//// .antMatchers("/swagger-ui.html").permitAll() +//// .antMatchers("/webjars/**").permitAll() +//// .antMatchers("/swagger-resources/**").permitAll() +// //.antMatchers("/admin/**").permitAll()//.hasAnyRole("admin","user","ROLE_admin","ROLE_user") +// +// .anyRequest().permitAll() +// //.and().formLogin().permitAll() +// .and().csrf().disable() +// //.cors().and().csrf().disable() // we use the filter..see below +// .exceptionHandling() +// .authenticationEntryPoint(restAuthenticationEntryPoint) +// .and() +// .logout(); +// // @formatter:on +// } +// +// +// @Bean +// public FilterRegistrationBean corsFilter() { +// +// UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); +// CorsConfiguration config = new CorsConfiguration(); +// config.setAllowCredentials(true); +// config.setAllowedOriginPatterns(Collections.singletonList("*")); +// config.addAllowedHeader("*"); +// config.addAllowedMethod("*"); +// config.addAllowedOriginPattern( "*" ); +// source.registerCorsConfiguration("/**", config); +// FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); +// +// bean.setOrder(0); +// +// return bean; +// +// } +// +// +// +//} diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index d31c35db973a5ce2f3b1ce3941492d79b4ca61be..41655a576fc6aa1934789e5d6ef48913d8e1767e 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -12,6 +12,7 @@ spring: name: org.etsi.osl.mcp.server version: 0.0.1 type: SYNC + protocol: STREAMABLE sse-message-endpoint: /mcp/messages stdio: false resource-change-notification: true @@ -32,7 +33,15 @@ spring: jwt: issuer-uri: http://keycloak:8080/auth/realms/openslice jwk-set-uri: http://keycloak:8080/auth/realms/openslice/.well-known/openid-configuration - + + +spring-addons: + issuers: + - uri: http://keycloak:8080/auth/realms/openslice + username-json-path: $.preferred_username + claims: + - jsonPath: $.realm_access.roles + - jsonPath: $.resource_access.*.roles logging: level: