# Pwsh Mcp Demo

> A lightweight Model Context Protocol (MCP) server implementation in PowerShell that exposes system information and management capabilities to AI assistants. Demonstrates JSON-RPC communication over stdio with tools for profile inspection, module discovery, and service management.

- **Type:** MCP server
- **Install:** `agentstack add mcp-cviorel-pwsh-mcp-demo`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [cviorel](https://agentstack.voostack.com/s/cviorel)
- **Installs:** 0
- **Category:** [Integrations](https://agentstack.voostack.com/c/integrations)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [cviorel](https://github.com/cviorel)
- **Source:** https://github.com/cviorel/pwsh-mcp-demo

## Install

```sh
agentstack add mcp-cviorel-pwsh-mcp-demo
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# PowerShell MCP Server Demo

[](https://github.com/PowerShell/PowerShell)
[](https://modelcontextprotocol.io)
[](LICENSE)

A lightweight, easy-to-understand demonstration of a Model Context Protocol (MCP) server implemented in PowerShell. This server exposes PowerShell system information and management capabilities through the standardized MCP interface, enabling AI assistants to interact with Windows environments.

## Table of Contents

- [Overview](#overview)
- [Features](#features)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Configuration](#configuration)
- [Usage](#usage)
  - [Available Tools](#available-tools)
  - [Available Resources](#available-resources)
  - [Example Prompts](#example-prompts)
- [Architecture](#architecture)
- [API Reference](#api-reference)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)
- [Support](#support)

## Overview

This project demonstrates how to build a functional MCP (Model Context Protocol) server using PowerShell. The server communicates via JSON-RPC over stdin/stdout, making it compatible with MCP-enabled AI assistants like Claude Desktop, Cline, and other MCP clients.

### What is MCP?

The Model Context Protocol (MCP) is an open standard that enables AI assistants to securely interact with local tools and data sources. This server implementation showcases:

- **JSON-RPC 2.0** communication over stdio
- **Tool exposure** for PowerShell operations
- **Resource management** for workspace information
- **Content-Length framing** with JSON-lines fallback
- **Minimal dependencies** for easy understanding and modification

### Why PowerShell?

PowerShell provides native access to Windows system information, making it ideal for:

- System administration tasks
- Module and service management
- Configuration inspection
- Cross-platform scripting (PowerShell Core)

## Features

✨ **Core Capabilities**

- **Profile Status Checking** - Inspect PowerShell profile files across all scopes
- **Module Discovery** - List installed PowerShell modules with pattern filtering
- **Service Management** - Query Windows services by status with configurable limits
- **Workspace Information** - Access current directory, user, and environment details

🔧 **Technical Features**

- **Dual Transport Modes** - Supports Content-Length framing and JSON-lines
- **Auto-Detection** - Automatically detects transport protocol
- **Debug Logging** - Comprehensive logging to stderr for troubleshooting
- **Error Handling** - Robust error responses with JSON-RPC error codes
- **Configurable Limits** - Prevents resource exhaustion with sensible defaults

## Prerequisites

### Required Software

- **PowerShell 7.0 or later** (PowerShell Core)
  - Download: [PowerShell Releases](https://github.com/PowerShell/PowerShell/releases)
  - Verify installation: `pwsh --version`

- **MCP-Compatible Client** (one of the following):
  - [Claude Desktop](https://claude.ai/download) - Anthropic's desktop application
  - [Cline VSCode Extension](https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev)
  - Any MCP-compatible client supporting stdio transport

### Operating System

- **Windows 10/11** - Full functionality (all tools available)
- **macOS/Linux** - Partial functionality (profile and module tools only; service tool unavailable)

### Optional Dependencies

- **Visual Studio Code** - For development and debugging
- **Git** - For cloning the repository

## Installation

### Option 1: Clone Repository

```powershell
# Clone or download the repository to your local machine

# Navigate to the directory
cd pwsh-mcp-demo

# Verify the server script exists
Test-Path ./mcp-server.ps1
```

### Option 2: Manual Download

1. Download [`mcp-server.ps1`](mcp-server.ps1) from this repository
2. Save it to a directory of your choice
3. Note the full path for configuration

### Verify Installation

```powershell
# Test the server responds to input
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05"}}' | pwsh ./mcp-server.ps1
```

You should see a JSON response with server information.

## Quick Start

Get the server running in under 5 minutes:

### Step 1: Configure Your MCP Client

#### For Claude Desktop

Edit your Claude Desktop configuration file:

**Windows:** `%APPDATA%\Claude\claude_desktop_config.json`

**macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`

Add this server configuration:

```json
{
  "mcpServers": {
    "pwsh-mcp-demo": {
      "command": "pwsh",
      "args": [
        "-NoProfile",
        "-ExecutionPolicy",
        "Bypass",
        "-File",
        "C:/path/to/pwsh-mcp-demo/mcp-server.ps1"
      ],
      "env": {
        "MCP_DEBUG": "true",
        "MCP_TRANSPORT_MODE": "auto"
      }
    }
  }
}
```

**Important:** Replace `C:/path/to/pwsh-mcp-demo/mcp-server.ps1` with the actual path to your server script.

#### For Cline (VSCode Extension)

Create or edit `.vscode/mcp.json` in your workspace:

```json
{
  "servers": {
    "pwsh-mcp-demo": {
      "type": "stdio",
      "command": "pwsh",
      "args": [
        "-NoProfile",
        "-ExecutionPolicy",
        "Bypass",
        "-File",
        "${workspaceFolder}/mcp-server.ps1"
      ],
      "env": {
        "MCP_DEBUG": "true",
        "MCP_TRANSPORT_MODE": "auto"
      }
    }
  }
}
```

### Step 2: Restart Your MCP Client

- **Claude Desktop:** Completely quit and restart the application
- **Cline:** Reload the VSCode window (`Ctrl+Shift+P` → "Developer: Reload Window")

### Step 3: Test the Connection

Try these prompts in your MCP client:

```
Check my PowerShell profile status
```

```
List installed PowerShell modules matching Az*
```

```
Show me 10 running Windows services
```

If you see results, congratulations! Your MCP server is working. 🎉

## Configuration

### Environment Variables

The server supports several environment variables for customization:

| Variable             | Values                            | Default | Description                    |
| :------------------- | :-------------------------------- | :------ | :----------------------------- |
| `MCP_DEBUG`          | `true`, `false`, `1`, `0`         | `true`  | Enable debug logging to stderr |
| `MCP_TRANSPORT_MODE` | `auto`, `content-length`, `jsonl` | `auto`  | Transport protocol mode        |

### Transport Modes Explained

- **`auto`** - Automatically detects Content-Length headers or falls back to JSON-lines
- **`content-length`** - Forces Content-Length framing (recommended for production)
- **`jsonl`** - Forces newline-delimited JSON (useful for manual testing)

### Debug Logging

When `MCP_DEBUG=true`, the server writes detailed logs to stderr:

```
[2026-02-16 20:35:27.123] [STARTUP] Starting pwsh-mcp-demo 1.0.0
[2026-02-16 20:35:27.456] [INFO] Received: {"jsonrpc":"2.0","id":1,"method":"initialize"...}
[2026-02-16 20:35:27.789] [INFO] Sent: {"jsonrpc":"2.0","id":1,"result":{...}}
```

**Tip:** Disable debug logging in production for better performance:

```json
"env": {
  "MCP_DEBUG": "false"
}
```

### Execution Policy

The server uses `-ExecutionPolicy Bypass` to ensure scripts run without policy restrictions. This is safe because:

- The server only executes its own code
- No external scripts are loaded
- User input is validated and sanitized

## Usage

### Available Tools

The server exposes three PowerShell tools through the MCP interface:

#### 1. `get_powershell_profile_status`

Retrieves information about PowerShell profile files across all scopes.

**Parameters:** None

**Returns:** JSON array with profile information including:

- Profile scope name
- Full file path
- Existence status
- File size (if exists)
- Last modified timestamp (if exists)

**Example Output:**

```json
[
  {
    "profile": "CurrentUserCurrentHost",
    "path": "C:\\Users\\YourName\\Documents\\PowerShell\\Microsoft.PowerShell_profile.ps1",
    "exists": true,
    "length": 2048,
    "lastWriteTime": "2026-02-15T10:30:00"
  },
  {
    "profile": "AllUsersAllHosts",
    "path": "C:\\Program Files\\PowerShell\\7\\profile.ps1",
    "exists": false,
    "length": null,
    "lastWriteTime": null
  }
]
```

#### 2. `list_installed_modules`

Lists installed PowerShell modules with optional wildcard filtering.

**Parameters:**

| Parameter     | Type   | Required | Description                               |
| :------------ | :----- | :------- | :---------------------------------------- |
| `namePattern` | string | No       | Wildcard pattern (e.g., `Az*`, `Pester*`) |

**Returns:** JSON array of modules (max 200) with:

- Module name
- Version number
- Module base path
- PowerShell edition compatibility

**Example Output:**

```json
[
  {
    "Name": "Az.Accounts",
    "Version": "2.15.1",
    "ModuleBase": "C:\\Program Files\\PowerShell\\Modules\\Az.Accounts\\2.15.1",
    "PSEdition": "Core"
  },
  {
    "Name": "Az.Storage",
    "Version": "6.1.0",
    "ModuleBase": "C:\\Program Files\\PowerShell\\Modules\\Az.Storage\\6.1.0",
    "PSEdition": "Core"
  }
]
```

#### 3. `get_windows_services`

Queries Windows services with status filtering and result limiting.

**Parameters:**

| Parameter | Type    | Required | Description                                             |
| :-------- | :------ | :------- | :------------------------------------------------------ |
| `status`  | string  | No       | Filter: `all`, `running`, or `stopped` (default: `all`) |
| `limit`   | integer | No       | Max results: 1-200 (default: 25)                        |

**Returns:** JSON array of services with:

- Service name
- Display name
- Current status
- Service type

**Example Output:**

```json
[
  {
    "Name": "EventLog",
    "DisplayName": "Windows Event Log",
    "Status": 4,
    "ServiceType": 16
  },
  {
    "Name": "Winmgmt",
    "DisplayName": "Windows Management Instrumentation",
    "Status": 4,
    "ServiceType": 16
  }
]
```

**Note:** Status codes: `1` = Stopped, `4` = Running

### Available Resources

#### `workspace://info`

Provides current workspace and environment information.

**URI:** `workspace://info`

**MIME Type:** `application/json`

**Returns:**

```json
{
  "currentDirectory": "C:\\Users\\YourName\\Projects\\pwsh-mcp-demo",
  "timestamp": "2026-02-16 20:35:27",
  "environment": {
    "user": "YourName",
    "computer": "DESKTOP-ABC123"
  }
}
```

### Example Prompts

Use these natural language prompts with your MCP client to interact with the server:

#### Profile Management

```
Check my PowerShell profile files and tell me which ones exist
```

```
Show me the size and last modified date of my PowerShell profiles
```

#### Module Discovery

```
List all installed PowerShell modules matching Az*
```

```
What PowerShell modules are installed on this system?
```

#### Service Management

```
List 25 running Windows services
```

```
Show me 50 stopped services
```

```
Get 10 services regardless of status
```

#### Workspace Information

```
Read workspace://info and show me the current directory
```

```
What's my current workspace information?
```

#### Multi-Step Operations

```
First check my PowerShell profiles, then list Az* modules, and summarize both
```

```
Get workspace info and list 15 running services, then create a system report
```

## Architecture

### High-Level Design

```
┌─────────────────────────────────────────────────────────────┐
│                        MCP Client                           │
│                  (Claude Desktop / Cline)                   │
└────────────────────────┬────────────────────────────────────┘
                         │ JSON-RPC over stdio
                         │ (Content-Length or JSON-lines)
                         ↓
┌─────────────────────────────────────────────────────────────┐
│                   PowerShell MCP Server                     │
│                                                             │
│  ┌─────────────────────────────────────────────────────┐  │
│  │              Transport Layer                        │  │
│  │  • Read-Message (stdin)                            │  │
│  │  • Write-Response (stdout)                         │  │
│  │  • Content-Length detection                        │  │
│  └─────────────────────────────────────────────────────┘  │
│                         ↓                                   │
│  ┌─────────────────────────────────────────────────────┐  │
│  │              Request Router                         │  │
│  │  • Invoke-Request (method dispatcher)              │  │
│  │  • JSON-RPC validation                             │  │
│  │  • Error handling                                  │  │
│  └─────────────────────────────────────────────────────┘  │
│                         ↓                                   │
│  ┌─────────────────────────────────────────────────────┐  │
│  │              Business Logic                         │  │
│  │  • Invoke-Tool (tool implementations)              │  │
│  │  • Get-ResourceContent (resource handler)          │  │
│  └─────────────────────────────────────────────────────┘  │
│                         ↓                                   │
│  ┌─────────────────────────────────────────────────────┐  │
│  │              PowerShell APIs                        │  │
│  │  • $PROFILE (profile paths)                        │  │
│  │  • Get-Module (module listing)                     │  │
│  │  • Get-Service (service queries)                   │  │
│  └─────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
```

### Request Lifecycle

1. **Read** - Server reads JSON-RPC request from stdin
2. **Parse** - Request is parsed and validated as JSON
3. **Route** - Method is dispatched to appropriate handler
4. **Execute** - Tool or resource logic runs
5. **Respond** - JSON-RPC response is written to stdout

### Key Components

| Component             | Purpose                | Location      |
| :-------------------- | :--------------------- | :------------ |
| `Start-McpServer`     | Main server loop       | Lines 497-531 |
| `Read-Message`        | Transport layer input  | Lines 214-268 |
| `Write-Response`      | Transport layer output | Lines 270-285 |
| `Invoke-Request`      | Method dispatcher      | Lines 381-495 |
| `Invoke-Tool`         | Tool implementations   | Lines 287-361 |
| `Get-ResourceContent` | Resource handler       | Lines 363-374 |

### Design Principles

- **Simplicity** - Minimal abstractions, easy to understand
- **Explicitness** - Clear function names and control flow
- **Modularity** - Separate concerns (transport, routing, logic)
- **Robustness** - Comprehensive error handling
- **Debuggability** - Detailed logging for troubleshooting

## API Reference

### Supported MCP Methods

| Method                      | Type         | Description                             |
| :-------------------------- | :----------- | :-------------------------------------- |
| `initialize`                | Request      | Initialize MCP session                  |
| `initialized`               | Notification | Session initialization complete         |
| `notifications/initialized` | Notification | Alternative initialization notification |
| `notifications/cancelled`   | Notification | Operation cancellation                  |
| `tools/list`                | Request      | List available tools                    |
| `tools/call`                | Request      | Execute a tool                          |
| `resources/list`            | Request      | List available resources                |
| `resources/read`            | Request      | Read a resource                         |

### JSON-RPC Error Codes

| Code     | Meaning          | When Used                  |
| :------- | :--------------- | :------------------------- |
| `-32700` | Parse error      | Invalid JSON received      |
| `-32600` |

…

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [cviorel](https://github.com/cviorel)
- **Source:** [cviorel/pwsh-mcp-demo](https://github.com/cviorel/pwsh-mcp-demo)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-cviorel-pwsh-mcp-demo
- Seller: https://agentstack.voostack.com/s/cviorel
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
