### Initialize Smithy MCP Server Project Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/mcp-server/README.md Initializes a new Smithy project using the MCP server template from a GitHub repository. Requires the Smithy CLI to be installed. ```bash smithy init -t mcp-server --url https://github.com/smithy-lang/smithy-java ``` ```bash smithy init -t mcp-server --url git@github.com:smithy-lang/smithy-java.git ``` -------------------------------- ### Run the Smithy Java Basic Server Project Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/basic-server/README.md Executes the Gradle build to run the basic Smithy Java server. The server will start listening on port 8080. ```console gradle run ``` -------------------------------- ### Initialize Smithy Java End-to-End Project Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/end-to-end/README.md Initializes a new Smithy Java project using the 'end-to-end' template from the smithy-java GitHub repository. Requires the Smithy CLI to be installed. This command sets up a project structure for generating both client and server components. ```console smithy init -t end-to-end --url https://github.com/smithy-lang/smithy-java ``` ```console smithy init -t end-to-end --url git@github.com:smithy-lang/smithy-java.git ``` -------------------------------- ### Run Smithy Java Integration Tests with Gradle Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/end-to-end/README.md Executes the integration tests for the Smithy Java project using the Gradle wrapper. These tests verify the functionality of the generated client against the generated server. The tests automatically start the server before execution. ```console gradle integ ``` -------------------------------- ### Initialize Dynamodb Client Example Project Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/dynamodb-client/README.md Command to initialize the dynamodb-client example project using the Smithy CLI. This command clones the project from a specified URL, allowing users to use it as a template for their own projects. ```console smithy init -t dynamodb-client --url https://github.com/smithy-lang/smithy-java ``` ```console smithy init -t dynamodb-client --url git@github.com:smithy-lang/smithy-java.git ``` -------------------------------- ### Initialize Smithy Java Basic Server Project Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/basic-server/README.md Initializes a new Smithy Java project for building a basic server using the Smithy CLI. This command fetches a template from a remote Git repository. ```console smithy init -t basic-server --url https://github.com/smithy-lang/smithy-java ``` ```console smithy init -t basic-server --url git@github.com:smithy-lang/smithy-java.git ``` -------------------------------- ### Smithy Service-Level Guidance Prompt Example Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/mcp-traits-example/README.md Provides an example of implementing service-level guidance using the @prompts trait, offering a high-level overview of the service's capabilities and conditions for its use. ```smithy @prompts({ service_overview: { description: "Overview of the user management service" template: "This service manages user accounts and provides search capabilities." preferWhen: "User needs general information about user management" } }) service UserService { // ... } ``` -------------------------------- ### Run Smithy MCP Server Implementations Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/mcp-server/README.md Executes the MCP server implementations (ProxyMCPExample or MCPServerExample) using the generated fat JAR. The command specifies the classpath and the main class to run. ```bash java -cp mcp-server-0.0.1-all.jar software.amazon.smithy.java.example.server.mcp.ProxyMCPExample ``` ```bash java -cp mcp-server-0.0.1-all.jar software.amazon.smithy.java.example.server.mcp.MCPServerExample ``` -------------------------------- ### Configure MCP Client to Invoke Proxy Server Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/mcp-server/README.md Example JSON configuration for an MCP client to connect to the Smithy proxy server. It specifies the command and arguments needed to launch the server, including the JAR path and main class. ```json { "mcpServers": { "smithy-mcp-server": { "command": "java", "args": [ "-cp", "/path/to/build/libs/mcp-server-0.0.1-all.jar", "software.amazon.smithy.java.example.server.mcp.ProxyMCPExample" ] } } } ``` -------------------------------- ### Smithy @prompts Trait Conditional Usage Example Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/mcp-traits-example/README.md Demonstrates the use of the 'preferWhen' field in the @prompts trait to provide contextual information for LLMs, guiding them on when to utilize a specific operation. ```smithy preferWhen: "User wants to find specific users or browse user lists" ``` -------------------------------- ### Smithy @prompts Trait Placeholder Example Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/mcp-traits-example/README.md Shows how to use template placeholders like {{parameterName}} to reference fields defined in the associated arguments structure, enabling dynamic prompt generation. ```smithy template: "Search for users where {{searchCriteria}}. Use pagination with limit={{limit}} if many results expected." arguments: SearchUsersInput ``` -------------------------------- ### Bash Script for Smithy Project Build Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/mcp-traits-example/README.md Command to initiate the Gradle build process for the Smithy project. This typically compiles code, processes models, and prepares artifacts. ```bash # From the example directory gradle build ``` -------------------------------- ### Smithy Model Example (main.smithy) Source: https://context7.com/smithy-lang/smithy-java/llms.txt An example Smithy model defining a 'CoffeeShop' service with operations like `GetMenu`, `CreateOrder`, and `GetOrder`, including resource definitions and error types. ```APIDOC ## Smithy Model Example ### Description Defines a 'CoffeeShop' service using the Smithy IDL, including operations, resources, and error types. This model serves as the input for code generation. ### Method Smithy IDL ### Endpoint N/A ### Parameters N/A ### Request Example ```smithy // model/main.smithy $version: "2" namespace com.example use aws.protocols#restJson1 @title("Coffee Shop Service") @restJson1 service CoffeeShop { version: "2024-08-23" operations: [GetMenu] resources: [Order] } @http(method: "GET", uri: "/menu") @readonly operation GetMenu { output := { @required items: CoffeeItems } } list CoffeeItems { member: CoffeeItem } structure CoffeeItem { @required type: CoffeeType description: String } @enum([ {value: "ESPRESSO", name: "Espresso"} {value: "LATTE", name: "Latte"} {value: "COLD_BREW", name: "ColdBrew"} ]) string CoffeeType resource Order { identifiers: {id: String} create: CreateOrder read: GetOrder } @http(method: "POST", uri: "/orders") operation CreateOrder { input := { @required coffeeType: CoffeeType } output := { @required id: String @required coffeeType: CoffeeType @required status: OrderStatus } } @http(method: "GET", uri: "/orders/{id}") @readonly operation GetOrder { input := { @required @httpLabel id: String } output := { @required id: String @required coffeeType: CoffeeType @required status: OrderStatus } errors: [OrderNotFound] } @error("client") @httpError(404) structure OrderNotFound { @required orderId: String message: String } enum OrderStatus { IN_PROGRESS COMPLETED CANCELLED } ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Get Beer from Service using curl Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/basic-server/README.md Sends a POST request to the '/get-beer' endpoint of the running Smithy Java server to retrieve beer details. It specifies the content type as JSON and provides the beer ID in the request body. ```console curl -H "content-type: application/json" -d '{"id": 1 }' -X POST localhost:8080/get-beer ``` -------------------------------- ### Build Smithy MCP Server Fat JAR with Gradle Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/mcp-server/README.md Builds a fat JAR file for the MCP server project using Gradle. This JAR includes all necessary dependencies to run an MCP StdIO server. Execute this command from the project's root directory. ```bash gradle build ``` -------------------------------- ### Dynamic Client Example Usage in Java Source: https://github.com/smithy-lang/smithy-java/blob/main/client/dynamic-client/README.md Demonstrates how to use the dynamic client to load a Smithy model, create a client, and call a service operation. It shows model loading, service identification, client construction with protocol and transport, input definition using Document, and calling the service. ```java var model = Model.assembler() .addImport("/path/to/model.json") .assemble() .unwrap(); var shapeId = ShapeId.from("com.example#CoffeeShop"); var client = DynamicClient.builder() .service(shapeId) .model(model) .protocol(new RestJsonClientProtocol(shapeId)) .transport(new JavaHttpClientTransport()) .endpointResolver(EndpointResolver.staticEndpoint("https://api.cafe.example.com")) .build(); var input = Document.createFromObject(Map.of("coffeeType", "COLD_BREW")); var result = client.call("CreateOrder", input).get(); System.out.println(result); ``` -------------------------------- ### Smithy Service with @prompts Trait Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/mcp-traits-example/README.md Defines a UserService with a service-level prompt for searching users, utilizing placeholders for input criteria and limit, and specifying conditions for preference. This demonstrates basic LLM guidance integration. ```smithy namespace com.example use smithy.ai#prompts @prompts({ search_users: { description: "Search for users in the system by various criteria", template: "Search for users where {{searchCriteria}}. Use pagination with limit={{limit}} if many results expected.", arguments: SearchUsersInput, preferWhen: "User wants to find specific users or browse user lists" } }) service UserService { operations: [ SearchUsers ] } operation SearchUsers { input: SearchUsersInput output: SearchUsersOutput } structure SearchUsersInput { searchCriteria: String limit: Integer } structure SearchUsersOutput { id: String } ``` -------------------------------- ### Smithy @prompts Trait Structure Definition Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/mcp-traits-example/README.md Illustrates the structure of a prompt template within the @prompts trait, including required fields like description and template, and optional fields such as arguments and preferWhen. ```smithy /* * Prompt template structure within the @prompts trait map. */ "prompt_name": { description: String // Required: Brief description of the prompt's purpose template: String // Required: The actual prompt template with placeholders arguments: ArgumentShape // Optional: Reference to structure defining parameters preferWhen: String // Optional: Condition describing when to use this prompt } ``` -------------------------------- ### Java Integration Tests for Smithy CoffeeShop API Source: https://context7.com/smithy-lang/smithy-java/llms.txt This Java code uses JUnit 5 for integration testing of a Smithy-generated CoffeeShop service. It includes setup and teardown methods for the server and client, and tests for getting the menu, creating and retrieving orders, handling not found errors, and concurrent order creation. Dependencies include JUnit 5, Java concurrency utilities, and Smithy runtime libraries. ```java package com.example.test; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; import java.net.URI; import java.util.concurrent.*; import java.net.Socket; import java.io.IOException; import java.time.Duration; import java.util.List; import java.util.Set; import java.util.HashSet; import java.util.concurrent.CopyOnWriteArrayList; public class IntegrationTest { private static ExecutorService serverExecutor; private static Server server; private CoffeeShopClient client; private static final URI ENDPOINT = URI.create("http://localhost:9999"); @BeforeAll static void startServer() throws InterruptedException { serverExecutor = Executors.newSingleThreadExecutor(); serverExecutor.execute(() -> { server = Server.builder() .endpoints(ENDPOINT) .addService(CoffeeShop.builder() .addGetMenuOperation(new GetMenuHandler()) .addCreateOrderOperation(new CreateOrderHandler()) .addGetOrderOperation(new GetOrderHandler()) .build()) .build(); server.start(); }); // Wait for server to be ready await().atMost(Duration.ofSeconds(10)) .until(() -> isServerListening(ENDPOINT)); } @BeforeEach void setupClient() { client = CoffeeShopClient.builder() .endpointResolver(EndpointResolver.staticEndpoint(ENDPOINT)) .build(); } @Test void testGetMenu() { GetMenuOutput menu = client.getMenu(GetMenuInput.builder().build()); assertNotNull(menu); assertFalse(menu.getItems().isEmpty()); CoffeeItem espresso = menu.getItems().stream() .filter(item -> item.getType().equals(CoffeeType.ESPRESSO)) .findFirst() .orElse(null); assertNotNull(espresso); assertNotNull(espresso.getDescription()); } @Test void testCreateAndGetOrder() { // Create order CreateOrderInput createRequest = CreateOrderInput.builder() .coffeeType(CoffeeType.LATTE) .build(); CreateOrderOutput createResponse = client.createOrder(createRequest); assertNotNull(createResponse.getId()); assertEquals(CoffeeType.LATTE, createResponse.getCoffeeType()); assertEquals(OrderStatus.IN_PROGRESS, createResponse.getStatus()); // Get order GetOrderInput getRequest = GetOrderInput.builder() .id(createResponse.getId()) .build(); GetOrderOutput getResponse = client.getOrder(getRequest); assertEquals(createResponse.getId(), getResponse.getId()); assertEquals(CoffeeType.LATTE, getResponse.getCoffeeType()); } @Test void testOrderNotFound() { GetOrderInput request = GetOrderInput.builder() .id("non-existent-order") .build(); OrderNotFound exception = assertThrows( OrderNotFound.class, () -> client.getOrder(request) ); assertEquals("non-existent-order", exception.getOrderId()); assertNotNull(exception.getMessage()); } @Test void testConcurrentOrders() throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(10); CountDownLatch latch = new CountDownLatch(10); List orderIds = new CopyOnWriteArrayList<>(); for (int i = 0; i < 10; i++) { executor.submit(() -> { try { CreateOrderOutput response = client.createOrder( CreateOrderInput.builder() .coffeeType(CoffeeType.ESPRESSO) .build() ); orderIds.add(response.getId()); } finally { latch.countDown(); } }); } assertTrue(latch.await(30, TimeUnit.SECONDS)); assertEquals(10, orderIds.size()); // Verify all orders are unique Set uniqueIds = new HashSet<>(orderIds); assertEquals(10, uniqueIds.size()); executor.shutdown(); } @AfterAll static void stopServer() throws Exception { if (server != null) { server.shutdown().get(30, TimeUnit.SECONDS); } if (serverExecutor != null) { serverExecutor.shutdownNow(); } } private static boolean isServerListening(URI uri) { try (Socket socket = new Socket(uri.getHost(), uri.getPort())) { return true; } catch (IOException e) { return false; } } } ``` -------------------------------- ### POST / Source: https://github.com/smithy-lang/smithy-java/blob/main/aws/aws-sigv4/src/test/resources/software/amazon/smithy/java/aws/client/auth/scheme/sigv4/signing/post-sts-header-before/signed.txt This endpoint represents a POST request to the root of the example.amazonaws.com. It includes common AWS security and date headers. ```APIDOC ## POST / ### Description This endpoint represents a POST request to the root of the example.amazonaws.com. It includes common AWS security and date headers such as `X-Amz-Security-Token`, `X-Amz-Date`, and `Authorization`. ### Method POST ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None specified in the example. ### Request Example ```http POST / HTTP/1.1 Host:example.amazonaws.com X-Amz-Security-Token:AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQWLWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGdQrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz+scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA== X-Amz-Date:20150830T123600Z Authorization:AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/service/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=85d96828115b5dc0cfc3bd16ad9e210dd772bbebba041836c64533a82be05ead ``` ### Response #### Success Response (200) No specific success response fields are detailed in the provided input. #### Response Example None provided. ``` -------------------------------- ### Add Beer to Service using curl Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/basic-server/README.md Sends a POST request to the '/add-beer' endpoint of the running Smithy Java server to add a new beer. It specifies the content type as JSON and provides the beer details in the request body. ```console curl -H "content-type: application/json" -d '{"beer":{"name": "wit", "quantity":2} }' -X POST localhost:8080/add-beer ``` -------------------------------- ### Bash Script for Smithy Build Validation Source: https://github.com/smithy-lang/smithy-java/blob/main/examples/mcp-traits-example/README.md Command to execute the Gradle build for validating the Smithy model and applying traits. This process ensures the model's correctness and the proper integration of custom traits like @prompts. ```bash # Run Smithy build to validate the model and traits gradle smithyBuild ``` -------------------------------- ### HTTP POST Request with AWS Signature V4 Source: https://github.com/smithy-lang/smithy-java/blob/main/aws/aws-sigv4/src/test/resources/software/amazon/smithy/java/aws/client/auth/scheme/sigv4/signing/post-sts-header-before/signed.txt An example of an HTTP POST request demonstrating the use of AWS Signature Version 4 for authenticating requests to AWS services. This includes essential headers like Host, X-Amz-Security-Token, X-Amz-Date, and the Authorization header which contains the computed signature. ```http POST / HTTP/1.1 Host:example.amazonaws.com X-Amz-Security-Token:AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQWLWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGdQrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz+scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA== X-Amz-Date:20150830T123600Z Authorization:AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/service/aws4_request, SignedHeaders=host;x-amz-date;x-amz-security-token, Signature=85d96828115b5dc0cfc3bd16ad9e210dd772bbebba041836c64533a82be05ead ``` -------------------------------- ### Implement and Register Smithy Java Server API Handlers Source: https://context7.com/smithy-lang/smithy-java/llms.txt Implement operation handler interfaces to define service logic. Register these handlers with the Server builder to process incoming requests. This example shows handlers for GetMenu, CreateOrder, and GetOrder operations, demonstrating request context access and modeled error throwing. ```java package com.example.server; import software.amazon.smithy.java.server.Server; import software.amazon.smithy.java.server.RequestContext; import software.amazon.smithy.java.example.etoe.service.*; import software.amazon.smithy.java.example.etoe.model.*; import java.net.URI; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; // Implement operation handlers class GetMenuHandler implements GetMenuOperation { private static final List MENU = List.of( CoffeeItem.builder() .type(CoffeeType.ESPRESSO) .description("Strong concentrated coffee") .build(), CoffeeItem.builder() .type(CoffeeType.LATTE) .description("Espresso with steamed milk") .build() ); @Override public GetMenuOutput getMenu(GetMenuInput input, RequestContext context) { // Access request metadata String clientId = context.get(RequestContext.CLIENT_IP).orElse("unknown"); System.out.println("Menu requested from: " + clientId); return GetMenuOutput.builder() .items(MENU) .build(); } } class CreateOrderHandler implements CreateOrderOperation { private final Map orders = new ConcurrentHashMap<>(); @Override public CreateOrderOutput createOrder(CreateOrderInput input, RequestContext context) { String orderId = UUID.randomUUID().toString(); Order order = new Order(orderId, input.getCoffeeType(), OrderStatus.IN_PROGRESS); orders.put(orderId, order); return CreateOrderOutput.builder() .id(orderId) .coffeeType(input.getCoffeeType()) .status(OrderStatus.IN_PROGRESS) .build(); } } class GetOrderHandler implements GetOrderOperation { private final Map orders; GetOrderHandler(Map orders) { this.orders = orders; } @Override public GetOrderOutput getOrder(GetOrderInput input, RequestContext context) throws OrderNotFound { Order order = orders.get(input.getId()); if (order == null) { // Throw modeled error throw OrderNotFound.builder() .orderId(input.getId()) .message("Order not found: " + input.getId()) .build(); } return GetOrderOutput.builder() .id(order.id()) .coffeeType(order.coffeeType()) .status(order.status()) .build(); } } // Build and start server public class CoffeeShopServer { public static void main(String[] args) { Map orderStore = new ConcurrentHashMap<>(); Server server = Server.builder() .endpoints(URI.create("http://0.0.0.0:8888")) .addService( CoffeeShop.builder() .addGetMenuOperation(new GetMenuHandler()) .addCreateOrderOperation(new CreateOrderHandler()) .addGetOrderOperation(new GetOrderHandler(orderStore)) .build() ) .build(); System.out.println("Starting CoffeeShop server on port 8888..."); server.start(); // Graceful shutdown hook Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { System.out.println("Shutting down server..."); server.shutdown().get(30, TimeUnit.SECONDS); } catch (Exception e) { System.err.println("Error during shutdown: " + e.getMessage()); } })); } } ``` -------------------------------- ### Create and Use MockClientPlugin in Java Source: https://github.com/smithy-lang/smithy-java/blob/main/client/client-mock-plugin/README.md Demonstrates how to set up and use the MockPlugin for intercepting client requests. It shows creating a queue of mock HTTP responses, initializing the plugin with this queue, and then creating a client that utilizes the plugin. Client requests will be served by the mock responses in order. ```java var mockQueue = new MockQueue(); mockQueue.enqueue( HttpResponse.builder() .statusCode(200) .body(DataStream.ofString("{\"id\":\"1\"}")) .build() ); mockQueue.enqueue( HttpResponse.builder() .statusCode(429) .body(DataStream.ofString("{\"__type\":\"InvalidSprocketId\"}")) .build() ); var mockPlugin = MockPlugin.builder().addQueue(mockQueue).build(); var client = SprocketClient.builder() .addPlugin(mockPlugin) .build(); var response = client.createSprocket(CreateSprocketRequest.builder().id(2).build()); var requests = mock.getRequests(); ``` -------------------------------- ### Gradle Plugin Configuration (build.gradle.kts) Source: https://context7.com/smithy-lang/smithy-java/llms.txt This snippet shows how to apply the Smithy Gradle plugin, add necessary dependencies for Java code generation, and configure source sets to include generated code. ```APIDOC ## Gradle Plugin Configuration ### Description Configure Smithy code generation in Gradle projects using the `smithy-base` plugin and specifying Java code generation plugins and runtime dependencies. ### Method Gradle Configuration (build.gradle.kts) ### Endpoint N/A ### Parameters N/A ### Request Example ```kotlin // build.gradle.kts plugins { id("software.amazon.smithy.gradle.smithy-base") version "1.0.0" java } repositories { mavenCentral() } dependencies { // Add code generation plugins smithyBuild("software.amazon.smithy.java:plugins:0.1.0") // Add runtime dependencies for generated code implementation("software.amazon.smithy.java:client-core:0.1.0") implementation("software.amazon.smithy.java:server-core:0.1.0") implementation("software.amazon.smithy.java:client-http:0.1.0") implementation("software.amazon.smithy.java:aws-client-restjson:0.1.0") } // Configure source sets to include generated code val smithy: SmithyExtension by extensions afterEvaluate { val clientPath = smithy.getPluginProjectionPath( smithy.sourceProjection.get(), "java-client-codegen" ) sourceSets.main.get().java.srcDir(clientPath) val serverPath = smithy.getPluginProjectionPath( smithy.sourceProjection.get(), "java-server-codegen" ) sourceSets.main.get().java.srcDir(serverPath) } tasks.named("compileJava") { dependsOn("smithyBuild") } ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Smithy Build Configuration (smithy-build.json) Source: https://context7.com/smithy-lang/smithy-java/llms.txt This snippet demonstrates the `smithy-build.json` configuration, specifying plugins for Java client and server code generation, including service details, namespaces, protocols, and header files. ```APIDOC ## Smithy Build Configuration ### Description Configure Smithy code generation plugins, including settings for Java client and server code generators, service definitions, namespaces, protocols, and header files. ### Method JSON Configuration (smithy-build.json) ### Endpoint N/A ### Parameters N/A ### Request Example ```json // smithy-build.json { "version": "1.0", "plugins": { "java-client-codegen": { "service": "com.example#CoffeeShop", "namespace": "com.example.coffeeshop.client", "protocol": "aws.protocols#restJson1", "headerFile": "license.txt" }, "java-server-codegen": { "service": "com.example#CoffeeShop", "namespace": "com.example.coffeeshop.server", "useExternalTypes": true, "headerFile": "license.txt" } }, "projections": { "client-only": { "plugins": { "java-client-codegen": { "service": "com.example#CoffeeShop" } } } } } ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Build and Use Smithy Java Type-Safe Service Clients Source: https://context7.com/smithy-lang/smithy-java/llms.txt Demonstrates building a Smithy Java client with custom configurations and making synchronous and asynchronous calls to service operations. It covers setting endpoints, transports, interceptors, and retry strategies. It also shows how to handle modeled errors and use request-level configuration overrides. ```java package com.example.client; import software.amazon.smithy.java.client.core.Client; import software.amazon.smithy.java.client.core.endpoint.EndpointResolver; import software.amazon.smithy.java.client.http.HttpClientTransport; import software.amazon.smithy.java.example.etoe.client.CoffeeShopClient; import software.amazon.smithy.java.example.etoe.model.*; // Build a client with custom configuration CoffeeShopClient client = CoffeeShopClient.builder() .endpoint("https://api.example.com") .endpointResolver(EndpointResolver.staticEndpoint(URI.create("http://localhost:8888"))) .transport(HttpClientTransport.builder().build()) .addInterceptor((hook) -> { System.out.println("Calling operation: " + hook.operation().name()); return null; }) .retryStrategy(RetryStrategy.standard()) .build(); // Call operations synchronously (blocks on CompletableFuture) GetMenuInput menuRequest = GetMenuInput.builder().build(); GetMenuOutput menuResponse = client.getMenu(menuRequest); List items = menuResponse.getItems(); items.forEach(item -> System.out.println(item.getType() + ": " + item.getDescription()) ); // Call operations asynchronously CreateOrderInput orderRequest = CreateOrderInput.builder() .coffeeType(CoffeeType.ESPRESSO) .build(); client.createOrderAsync(orderRequest) .thenAccept(response -> { System.out.println("Order ID: " + response.getId()); System.out.println("Status: " + response.getStatus()); }) .exceptionally(throwable -> { if (throwable.getCause() instanceof OrderException) { System.err.println("Order failed: " + throwable.getMessage()); } return null; }); // Handle modeled errors try { GetOrderInput getRequest = GetOrderInput.builder() .id("invalid-order-id") .build(); GetOrderOutput order = client.getOrder(getRequest); } catch (OrderNotFound e) { System.err.println("Order not found: " + e.getOrderId()); System.err.println("Message: " + e.getMessage()); } // Use request-level configuration overrides CreateOrderOutput response = client.createOrder( orderRequest, requestOverride -> requestOverride .endpoint(URI.create("https://backup.example.com")) .putConfig(ClientContext.TIMEOUT, Duration.ofSeconds(30)) ); ``` -------------------------------- ### Configure Smithy Gradle Plugin and Code Generation - Kotlin Source: https://context7.com/smithy-lang/smithy-java/llms.txt This Kotlin script configures the Smithy Gradle plugin, defines dependencies for Java client and server code generation, and sets up source directories for generated code. It ensures that Java compilation depends on the Smithy build task. Dependencies include smithy-base, and various Java runtime libraries. ```kotlin // build.gradle.kts plugins { id("software.amazon.smithy.gradle.smithy-base") version "1.0.0" java } repositories { mavenCentral() } dependencies { // Add code generation plugins smithyBuild("software.amazon.smithy.java:plugins:0.1.0") // Add runtime dependencies for generated code implementation("software.amazon.smithy.java:client-core:0.1.0") implementation("software.amazon.smithy.java:server-core:0.1.0") implementation("software.amazon.smithy.java:client-http:0.1.0") implementation("software.amazon.smithy.java:aws-client-restjson:0.1.0") } // Configure source sets to include generated code val smithy: SmithyExtension by extensions afterEvaluate { val clientPath = smithy.getPluginProjectionPath( smithy.sourceProjection.get(), "java-client-codegen" ) sourceSets.main.get().java.srcDir(clientPath) val serverPath = smithy.getPluginProjectionPath( smithy.sourceProjection.get(), "java-server-codegen" ) sourceSets.main.get().java.srcDir(serverPath) } tasks.named("compileJava") { dependsOn("smithyBuild") } ``` -------------------------------- ### Configure Smithy Build for Java Client Codegen Source: https://github.com/smithy-lang/smithy-java/blob/main/README.md This snippet shows how to configure the `smithy-build.json` file to use the `java-client-codegen` plugin. It specifies the service, namespace, and an optional header file for generated code. ```json { "plugins": { "java-client-codegen": { "service": "com.example#CoffeeShop", "namespace": "software.amazon.smithy.java.examples", "headerFile": "license.txt" } } } ``` -------------------------------- ### Apply Smithy Gradle Plugin Source: https://github.com/smithy-lang/smithy-java/blob/main/README.md This snippet shows how to apply the smithy-base Gradle plugin to a project. It requires specifying the plugin ID and version. ```kotlin plugins { id("software.amazon.smithy.gradle.smithy-base") version "" } ``` -------------------------------- ### Add waiters-codegen Dependencies (Kotlin) Source: https://github.com/smithy-lang/smithy-java/blob/main/codegen/integrations/waiters-codegen/README.md Integrates the waiters-codegen module into your Smithy build process. This involves adding the codegen integration as a smithy-build dependency and the waiters core package as a runtime dependency. Ensure you replace `` with the appropriate version number. ```kotlin dependencies { // Add codegen integration as a smithy-build dependency, so it can be // discovered by the client codegen plugin smithyBuild("software.amazon.smithy.java.codegen:waiters:") // Add waiters core package as a runtime dependency implementation("software.amazon.smithy.java:waiters:") } ``` -------------------------------- ### Implement Protocol Test Handlers (Java) Source: https://github.com/smithy-lang/smithy-java/blob/main/protocol-test-harness/README.md Provides implementations for protocol test handlers. Client request and server response handlers compare wire data, while client response and server request handlers execute provided runnables. These are annotated with `@HttpClientRequestTests`, `@HttpServerResponseTests`, `@HttpClientResponseTests`, and `@HttpServerRequestTests` respectively. ```java import software.amazon.smithy.java.testing.protocol.tests.HttpClientRequestTests; import software.amazon.smithy.java.testing.protocol.tests.HttpServerResponseTests; import software.amazon.utils.DataStream; @HttpClientRequestTests public void requestTest(DataStream expected, DataStream actual) { // Add logic to compare equality here... } @HttpServerResponseTests public void responseTest(DataStream expected, DataStream actual) { // Add logic to compare equality here... } ``` ```java import software.amazon.smithy.java.testing.protocol.tests.HttpClientResponseTests; import software.amazon.smithy.java.testing.protocol.tests.HttpServerRequestTests; @HttpClientResponseTests public void requestTest(Runnable test) { test.run(); } @HttpServerRequestTests public void requestTest(Runnable test) { test.run(); } ``` -------------------------------- ### Configure Source Set for Generated Client Code Source: https://github.com/smithy-lang/smithy-java/blob/main/README.md This Kotlin code snippet configures the Gradle build to include the generated client code in the main source set. It ensures that the generated client files are available for Java compilation. ```kotlin afterEvaluate { val clientPath = smithy.getPluginProjectionPath(smithy.sourceProjection.get(), "java-client-codegen") sourceSets.main.get().java.srcDir(clientPath) } // Ensure client files are generated before java compilation is executed. tasks.named("compileJava") { dependsOn("smithyBuild") } ``` -------------------------------- ### Configure Smithy Code Generation Parameters - JSON Source: https://context7.com/smithy-lang/smithy-java/llms.txt This JSON file configures the Smithy code generation plugins for Java. It specifies the service, namespace, protocol, and header file for both client and server code generation. It also demonstrates how to define projections for specific generation tasks. The configuration is used by the Smithy build tool. ```json // smithy-build.json { "version": "1.0", "plugins": { "java-client-codegen": { "service": "com.example#CoffeeShop", "namespace": "com.example.coffeeshop.client", "protocol": "aws.protocols#restJson1", "headerFile": "license.txt" }, "java-server-codegen": { "service": "com.example#CoffeeShop", "namespace": "com.example.coffeeshop.server", "useExternalTypes": true, "headerFile": "license.txt" } }, "projections": { "client-only": { "plugins": { "java-client-codegen": { "service": "com.example#CoffeeShop" } } } } } ``` -------------------------------- ### Add RPCv2 CBOR Client Dependency to Java Project Source: https://github.com/smithy-lang/smithy-java/blob/main/client/client-rpcv2-cbor/README.md This snippet shows how to add the `client-rpcv2-cbor` module as an implementation dependency in a Java project's build file, typically using Gradle. This makes the RPCv2 CBOR protocol available for client generation. ```gradle dependencies { + implementation("software.amazon.smithy.java:client-rpcv2-cbor") } ``` -------------------------------- ### Add Smithy Java Codegen Plugins as Dependency Source: https://github.com/smithy-lang/smithy-java/blob/main/README.md This snippet demonstrates how to add the Smithy Java codegen plugins as a dependency to the `smithyBuild` configuration in Gradle. This makes the plugins discoverable by the Smithy build process. ```kotlin dependencies { smithyBuild("software.amazon.smithy.java:plugins:") } ``` -------------------------------- ### Manually Create and Use a Smithy Java Waiter Source: https://github.com/smithy-lang/smithy-java/blob/main/client/client-waiters/README.md Demonstrates how to manually construct a waiter in Java. This involves defining failure conditions using matchers and then invoking the wait operation with input and a timeout duration. Dependencies include the Smithy runtime library. ```java var waiter = Waiter.builder(client::getFoosSync) .failure(Matcher.output(o -> o.status().equals("FAILED"))) .build(); waiter.wait(input, Duration.ofSeconds(2)); ``` -------------------------------- ### Configure Java Client Codegen to Use RPCv2 CBOR Protocol Source: https://github.com/smithy-lang/smithy-java/blob/main/client/client-rpcv2-cbor/README.md This snippet illustrates how to configure the `java-client-codegen` plugin in a project's codegen configuration file to set the `smithy.protocols#rpcv2Cbor` as the default protocol. This ensures generated clients will use the RPCv2 CBOR protocol. ```json { "version": "1.0", "plugins": { "java-client-codegen": { "service": "com.example#CoffeeShop", "namespace": "com.example.cafe", + "protocol": "smithy.protocols#rpcv2Cbor" } } } ``` -------------------------------- ### Create and Validate Smithy Schemas in Java Source: https://context7.com/smithy-lang/smithy-java/llms.txt Demonstrates how to create and define validation constraints for Smithy schemas (like strings and structures) using the Smithy Java runtime. This includes setting length and pattern traits for strings, defining required and optional members for structures, and handling recursive schema definitions. The generated `Schema` objects are precomputed for performance. ```java package software.amazon.smithy.java.core.schema; import software.amazon.smithy.model.shapes.ShapeId; import software.amazon.smithy.model.traits.*; // Create a simple string schema with validation Schema nameSchema = Schema.createString( ShapeId.from("com.example#Name"), LengthTrait.builder().min(1L).max(100L).build(), PatternTrait.builder().pattern("^[a-zA-Z]+$").build() ); // Create a structure schema with required and optional members Schema personSchema = Schema.structureBuilder(ShapeId.from("com.example#Person")) .putMember("name", nameSchema, new RequiredTrait()) .putMember("age", Schema.createInteger(ShapeId.from("com.example#Age"))) .putMember("email", Schema.createString(ShapeId.from("com.example#Email"))) .builderSupplier(() -> PersonBuilder.create()) .build(); // Access schema metadata ShapeId id = personSchema.id(); // "com.example#Person" ShapeType type = personSchema.type(); // STRUCTURE List members = personSchema.members(); // All member schemas // Check traits on schema if (personSchema.hasTrait(TraitKey.REQUIRED_TRAIT)) { RequiredTrait trait = personSchema.getTrait(TraitKey.REQUIRED_TRAIT); } // Create recursive structures using SchemaBuilder SchemaBuilder treeBuilder = Schema.structureBuilder(ShapeId.from("com.example#TreeNode")); treeBuilder.putMember("value", Schema.createString(ShapeId.from("com.example#Value"))); treeBuilder.putMember("children", Schema.listBuilder(ShapeId.from("com.example#Children")) .putMember("member", treeBuilder) // Self-reference .build() ); Schema treeSchema = treeBuilder.build().resolve(); ```