> ## Documentation Index
> Fetch the complete documentation index at: https://docs.go-mizu.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Reference

> Complete reference for all Contract v2 functions, types, and options

# API Reference

This page documents all public functions, types, and options in the Contract v2 package.

## Main Package

Import: `github.com/go-mizu/mizu/contract/v2`

### Functions

#### Register

Registers a Go interface implementation as a Contract service.

```go theme={null}
func Register[T any](impl T, opts ...Option) *RegisteredService
```

| Parameter | Type           | Description                                      |
| --------- | -------------- | ------------------------------------------------ |
| `T`       | type parameter | The interface type that defines your API         |
| `impl`    | `T`            | Your implementation that satisfies the interface |
| `opts`    | `...Option`    | Optional configuration                           |

**Returns:** `*RegisteredService` for mounting on transports.

**Example:**

```go theme={null}
// todo/api.go - Your interface is defined in a package
// type API interface {
//     Create(ctx context.Context, in *CreateInput) (*Todo, error)
//     List(ctx context.Context) (*ListOutput, error)
// }

impl := todo.NewService()
svc := contract.Register[todo.API](impl,
    contract.WithName("Todo"),
    contract.WithDefaultResource("todos"),
)
```

***

### Types

#### RegisteredService

A registered service ready to be mounted on transports.

```go theme={null}
type RegisteredService struct {
    // ... internal fields
}
```

**Methods:**

| Method                               | Returns              | Description                      |
| ------------------------------------ | -------------------- | -------------------------------- |
| `Descriptor()`                       | `*ServiceDescriptor` | Get service metadata             |
| `Call(ctx, resource, method, input)` | `(any, error)`       | Invoke a method programmatically |
| `NewInput(resource, method)`         | `(any, error)`       | Create new input instance        |

***

#### ServiceDescriptor

Metadata about a registered service.

```go theme={null}
type ServiceDescriptor struct {
    Name        string      // Service name
    Description string      // Optional description
    Resources   []*Resource // All resources
    Types       []*TypeInfo // All discovered types
}
```

***

#### Resource

A group of related methods (e.g., "todos").

```go theme={null}
type Resource struct {
    Name    string    // Resource name (e.g., "todos")
    Methods []*Method // Methods in this resource
}
```

***

#### Method

Metadata for a single method.

```go theme={null}
type Method struct {
    Name        string       // Method name (e.g., "create")
    Description string       // Optional description
    Input       *TypeInfo    // Input type (nil if no input)
    Output      *TypeInfo    // Output type (nil if no output)
    HTTP        *HTTPBinding // HTTP method and path
    Stream      StreamMode   // Streaming mode if any
}
```

***

#### TypeInfo

Information about a type used in the API.

```go theme={null}
type TypeInfo struct {
    Name   string         // Type name (e.g., "CreateInput")
    Kind   string         // Type kind (struct, slice, etc.)
    Schema map[string]any // JSON Schema
}
```

***

#### HTTPBinding

HTTP method and path for a method.

```go theme={null}
type HTTPBinding struct {
    Method string // HTTP method (GET, POST, etc.)
    Path   string // URL path pattern
}
```

***

### Options

#### WithName

Sets the service name:

```go theme={null}
contract.WithName("Todo")
```

#### WithDescription

Sets the service description:

```go theme={null}
contract.WithDescription("Todo management API")
```

#### WithDefaultResource

Groups all methods under a resource name:

```go theme={null}
contract.WithDefaultResource("todos")
```

#### WithResource

Groups specific methods under a resource:

```go theme={null}
contract.WithResource("users", "CreateUser", "GetUser", "ListUsers")
```

#### WithMethodHTTP

Override HTTP binding for a method:

```go theme={null}
contract.WithMethodHTTP("Archive", "POST", "/todos/{id}/archive")
```

#### WithHTTP

Set HTTP bindings for multiple methods:

```go theme={null}
contract.WithHTTP(map[string]contract.HTTPBinding{
    "Create": {Method: "POST", Path: "/v1/todos"},
    "Get":    {Method: "GET", Path: "/v1/todos/{id}"},
})
```

#### WithDefaults

Set global defaults:

```go theme={null}
contract.WithDefaults(contract.Defaults{
    BaseURL: "https://api.example.com",
})
```

#### WithStreaming

Mark a method as streaming:

```go theme={null}
contract.WithStreaming("Chat", contract.StreamSSE)
```

**Usage Example:**

```go theme={null}
svc := contract.Register[TodoAPI](impl,
    contract.WithName("Todo"),
    contract.WithDescription("Manages todo items"),
    contract.WithDefaultResource("todos"),
)
```

***

## REST Package

Import: `github.com/go-mizu/mizu/contract/v2/transport/rest`

### Functions

#### Mount

Mounts REST endpoints on a router.

```go theme={null}
func Mount(router *mizu.Router, svc *contract.RegisteredService, opts ...Option)
```

| Parameter | Type                 | Description            |
| --------- | -------------------- | ---------------------- |
| `router`  | `*mizu.Router`       | Mizu router            |
| `svc`     | `*RegisteredService` | Registered service     |
| `opts`    | `...Option`          | Optional configuration |

**Endpoints created based on method names:**

* `Create` -> `POST /{resource}`
* `List` -> `GET /{resource}`
* `Get` -> `GET /{resource}/{id}`
* `Update` -> `PUT /{resource}/{id}`
* `Delete` -> `DELETE /{resource}/{id}`

**Example:**

```go theme={null}
rest.Mount(app.Router, svc)
// Creates: POST /todos, GET /todos, GET /todos/{id}, PUT /todos/{id}, DELETE /todos/{id}
```

***

#### NewHandler

Creates an HTTP handler for the service.

```go theme={null}
func NewHandler(svc *contract.RegisteredService, opts ...Option) http.Handler
```

***

### Options

```go theme={null}
// Custom invoker (for middleware)
rest.WithInvoker(invoker)

// Custom path prefix
rest.WithPrefix("/api/v1")
```

***

## JSON-RPC Package

Import: `github.com/go-mizu/mizu/contract/v2/transport/jsonrpc`

### Functions

#### Mount

Mounts a JSON-RPC 2.0 endpoint.

```go theme={null}
func Mount(router *mizu.Router, path string, svc *contract.RegisteredService, opts ...Option)
```

| Parameter | Type                 | Description               |
| --------- | -------------------- | ------------------------- |
| `router`  | `*mizu.Router`       | Mizu router               |
| `path`    | `string`             | URL path for the endpoint |
| `svc`     | `*RegisteredService` | Registered service        |
| `opts`    | `...Option`          | Optional configuration    |

**Example:**

```go theme={null}
jsonrpc.Mount(app.Router, "/rpc", svc)
// Methods available as: todos.create, todos.list, todos.get, etc.
```

***

#### NewHandler

Creates a JSON-RPC HTTP handler.

```go theme={null}
func NewHandler(svc *contract.RegisteredService, opts ...Option) http.Handler
```

***

### Options

```go theme={null}
// Custom invoker (for middleware)
jsonrpc.WithInvoker(invoker)
```

***

### Types

#### Request

```go theme={null}
type Request struct {
    JSONRPC string          `json:"jsonrpc"`
    ID      any             `json:"id,omitempty"`
    Method  string          `json:"method"`
    Params  json.RawMessage `json:"params,omitempty"`
}
```

#### Response

```go theme={null}
type Response struct {
    JSONRPC string `json:"jsonrpc"`
    ID      any    `json:"id,omitempty"`
    Result  any    `json:"result,omitempty"`
    Error   *Error `json:"error,omitempty"`
}
```

#### Error

```go theme={null}
type Error struct {
    Code    int    `json:"code"`
    Message string `json:"message"`
    Data    any    `json:"data,omitempty"`
}
```

***

## MCP Package

Import: `github.com/go-mizu/mizu/contract/v2/transport/mcp`

### Functions

#### Mount

Mounts MCP endpoint.

```go theme={null}
func Mount(router *mizu.Router, path string, svc *contract.RegisteredService, opts ...Option)
```

**Example:**

```go theme={null}
mcp.Mount(app.Router, "/mcp", svc)
```

***

#### NewHandler

Creates an MCP HTTP handler.

```go theme={null}
func NewHandler(svc *contract.RegisteredService, opts ...Option) http.Handler
```

***

### Options

```go theme={null}
// Server information
mcp.WithServerInfo(mcp.ServerInfo{
    Name:    "my-api",
    Version: "1.0.0",
})

// Instructions for AI
mcp.WithInstructions("Use these tools to manage todos.")

// Allowed CORS origins
mcp.WithAllowedOrigins("https://claude.ai")

// Custom invoker (for middleware)
mcp.WithInvoker(invoker)
```

***

### Types

#### ServerInfo

```go theme={null}
type ServerInfo struct {
    Name    string `json:"name"`
    Version string `json:"version"`
}
```

***

## OpenAPI Package

Import: `github.com/go-mizu/mizu/contract/v2/transport/openapi`

### Functions

#### Mount

Mounts OpenAPI spec endpoint.

```go theme={null}
func Mount(router *mizu.Router, path string, svc *contract.RegisteredService)
```

**Example:**

```go theme={null}
openapi.Mount(app.Router, "/openapi.json", svc)
```

***

#### Generate

Generates OpenAPI document from service.

```go theme={null}
func Generate(svc *contract.RegisteredService) *Document
```

***

## Error Types

### Error

Contract error with code and message.

```go theme={null}
type Error struct {
    Code    ErrorCode      `json:"code"`
    Message string         `json:"message"`
    Details map[string]any `json:"details,omitempty"`
}
```

**Methods:**

| Method                   | Returns  | Description                        |
| ------------------------ | -------- | ---------------------------------- |
| `Error()`                | `string` | Error message (implements `error`) |
| `HTTPStatus()`           | `int`    | HTTP status code                   |
| `JSONRPCCode()`          | `int`    | JSON-RPC error code                |
| `Unwrap()`               | `error`  | Wrapped cause                      |
| `WithDetail(key, value)` | `*Error` | Add detail                         |
| `WithDetails(map)`       | `*Error` | Add multiple details               |
| `WithCause(err)`         | `*Error` | Wrap underlying error              |

***

### Error Constructors

Convenience functions for common errors:

```go theme={null}
contract.ErrNotFound(message string) *Error           // 404
contract.ErrInvalidArgument(message string) *Error    // 400
contract.ErrPermissionDenied(message string) *Error   // 403
contract.ErrUnauthenticated(message string) *Error    // 401
contract.ErrInternal(message string) *Error           // 500
contract.ErrAlreadyExists(message string) *Error      // 409
contract.ErrResourceExhausted(message string) *Error  // 429
contract.ErrUnimplemented(message string) *Error      // 501
contract.ErrUnavailable(message string) *Error        // 503
```

General constructors:

```go theme={null}
contract.NewError(code ErrorCode, message string) *Error
contract.Errorf(code ErrorCode, format string, args ...any) *Error
```

***

### ErrorCode

All available error codes:

```go theme={null}
type ErrorCode string

const (
    ErrCodeOK                 ErrorCode = "OK"
    ErrCodeCanceled           ErrorCode = "CANCELED"
    ErrCodeUnknown            ErrorCode = "UNKNOWN"
    ErrCodeInvalidArgument    ErrorCode = "INVALID_ARGUMENT"
    ErrCodeDeadlineExceeded   ErrorCode = "DEADLINE_EXCEEDED"
    ErrCodeNotFound           ErrorCode = "NOT_FOUND"
    ErrCodeAlreadyExists      ErrorCode = "ALREADY_EXISTS"
    ErrCodePermissionDenied   ErrorCode = "PERMISSION_DENIED"
    ErrCodeResourceExhausted  ErrorCode = "RESOURCE_EXHAUSTED"
    ErrCodeFailedPrecondition ErrorCode = "FAILED_PRECONDITION"
    ErrCodeAborted            ErrorCode = "ABORTED"
    ErrCodeOutOfRange         ErrorCode = "OUT_OF_RANGE"
    ErrCodeUnimplemented      ErrorCode = "UNIMPLEMENTED"
    ErrCodeInternal           ErrorCode = "INTERNAL"
    ErrCodeUnavailable        ErrorCode = "UNAVAILABLE"
    ErrCodeDataLoss           ErrorCode = "DATA_LOSS"
    ErrCodeUnauthenticated    ErrorCode = "UNAUTHENTICATED"
)
```

***

### Helper Functions

```go theme={null}
// Convert error to Contract error
contract.AsError(err error) *Error

// Convert HTTP status to error code
contract.HTTPStatusToErrorCode(status int) ErrorCode
```

***

## Method Signatures

Contract recognizes these method patterns:

### Pattern 1: Input and Output

```go theme={null}
func (s *Service) Create(ctx context.Context, in *CreateInput) (*Todo, error)
```

### Pattern 2: Output Only

```go theme={null}
func (s *Service) List(ctx context.Context) (*ListOutput, error)
```

### Pattern 3: Input Only

```go theme={null}
func (s *Service) Delete(ctx context.Context, in *DeleteInput) error
```

### Pattern 4: Neither

```go theme={null}
func (s *Service) Health(ctx context.Context) error
```

**Rules:**

* First parameter must be `context.Context`
* Input (if any) must be a pointer to a struct
* Last return value must be `error`
* Output (if any) must be a pointer to a struct

***

## Complete Example

This example shows a complete application using the recommended package-based organization:

```go theme={null}
// todo/types.go
package todo

type Todo struct {
    ID    string `json:"id"`
    Title string `json:"title"`
}

type CreateInput struct {
    Title string `json:"title"`
}

type GetInput struct {
    ID string `json:"id" path:"id"`
}

type DeleteInput struct {
    ID string `json:"id" path:"id"`
}

type ListOutput struct {
    Items []*Todo `json:"items"`
}
```

```go theme={null}
// todo/api.go
package todo

import "context"

// API defines the contract for todo operations
type API interface {
    Create(ctx context.Context, in *CreateInput) (*Todo, error)
    List(ctx context.Context) (*ListOutput, error)
    Get(ctx context.Context, in *GetInput) (*Todo, error)
    Delete(ctx context.Context, in *DeleteInput) error
}
```

```go theme={null}
// todo/service.go
package todo

import (
    "context"

    contract "github.com/go-mizu/mizu/contract/v2"
)

// Service implements todo.API
type Service struct{}

// Compile-time check
var _ API = (*Service)(nil)

func NewService() *Service {
    return &Service{}
}

func (s *Service) Create(ctx context.Context, in *CreateInput) (*Todo, error) {
    if in.Title == "" {
        return nil, contract.ErrInvalidArgument("title is required")
    }
    return &Todo{ID: "1", Title: in.Title}, nil
}

func (s *Service) List(ctx context.Context) (*ListOutput, error) {
    return &ListOutput{Items: []*Todo{}}, nil
}

func (s *Service) Get(ctx context.Context, in *GetInput) (*Todo, error) {
    return &Todo{ID: in.ID, Title: "Sample"}, nil
}

func (s *Service) Delete(ctx context.Context, in *DeleteInput) error {
    return nil
}
```

```go theme={null}
// main.go
package main

import (
    "github.com/go-mizu/mizu"
    contract "github.com/go-mizu/mizu/contract/v2"
    "github.com/go-mizu/mizu/contract/v2/transport/rest"
    "github.com/go-mizu/mizu/contract/v2/transport/jsonrpc"
    "github.com/go-mizu/mizu/contract/v2/transport/mcp"
    "github.com/go-mizu/mizu/contract/v2/transport/openapi"

    "yourapp/todo"
)

func main() {
    impl := todo.NewService()

    // Register
    svc := contract.Register[todo.API](impl,
        contract.WithName("Todo"),
        contract.WithDefaultResource("todos"),
    )

    // Create app
    app := mizu.New()

    // Mount transports
    rest.Mount(app.Router, svc)
    jsonrpc.Mount(app.Router, "/rpc", svc)
    mcp.Mount(app.Router, "/mcp", svc)
    openapi.Mount(app.Router, "/openapi.json", svc)

    app.Listen(":8080")
}
```

## See Also

* [Quick Start](/contract/quick-start) - Get started quickly
* [Services](/contract/service) - Method signatures in detail
* [Errors](/contract/errors) - Error patterns
* [Overview](/contract/transports-overview) - All transports
