Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
258 changes: 258 additions & 0 deletions samples/agent/mcp/apps/calculator.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
<!DOCTYPE html>
<!--
Copyright 2025 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MCP Calculator</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
}
.calculator {
background: #fff;
padding: 20px;
border-radius: 12px;
box-shadow: 0 4px 10px rgba(0,0,0,0.1);
width: 300px;
}
.display {
width: 100%;
height: 60px;
margin-bottom: 20px;
border: 1px solid #ddd;
border-radius: 8px;
font-size: 2em;
text-align: right;
padding: 10px;
box-sizing: border-box;
overflow-x: auto;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
button {
padding: 15px;
font-size: 1.2em;
border: none;
border-radius: 8px;
cursor: pointer;
background-color: #e0e0e0;
transition: background-color 0.2s;
}
button:hover {
background-color: #d0d0d0;
}
button.operator {
background-color: #ff9f0a;
color: white;
}
button.operator:hover {
background-color: #e08900;
}
button.equals {
background-color: #34c759;
color: white;
grid-column: span 2;
}
button.equals:hover {
background-color: #2da84e;
}
button.clear {
background-color: #ff3b30;
color: white;
grid-column: span 2;
}
button.clear:hover {
background-color: #d6332a;
}
</style>
</head>
<body>

<div class="calculator">
<div class="display" id="display">0</div>
<div class="buttons">
<button class="clear" onclick="clearDisplay()">AC</button>
<button class="operator" onclick="appendOperator('/')">÷</button>
<button class="operator" onclick="appendOperator('*')">×</button>
<button onclick="appendNumber('7')">7</button>
<button onclick="appendNumber('8')">8</button>
<button onclick="appendNumber('9')">9</button>
<button class="operator" onclick="appendOperator('-')">-</button>
<button onclick="appendNumber('4')">4</button>
<button onclick="appendNumber('5')">5</button>
<button onclick="appendNumber('6')">6</button>
<button class="operator" onclick="appendOperator('+')">+</button>
<button onclick="appendNumber('1')">1</button>
<button onclick="appendNumber('2')">2</button>
<button onclick="appendNumber('3')">3</button>
<button class="equals" onclick="calculate()">=</button>
<button onclick="appendNumber('0')">0</button>
<button onclick="appendPoint()">.</button>
Comment on lines +99 to +115

This comment was marked as spam.

</div>
</div>

<script>
let currentInput = '';
let previousInput = '';
let operator = null;
const displayElement = document.getElementById('display');

function updateDisplay() {
displayElement.textContent = currentInput || '0';
}

function appendNumber(number) {
if (currentInput === '0' && number !== '.') {
currentInput = number;
} else {
currentInput += number;
}
updateDisplay();
}

function appendPoint() {
if (!currentInput.includes('.')) {
currentInput += '.';
updateDisplay();
}
}

function appendOperator(op) {
if (currentInput === '') return;
if (previousInput !== '') {
calculate();
}
operator = op;
previousInput = currentInput;
currentInput = '';
}

function clearDisplay() {
currentInput = '';
previousInput = '';
operator = null;
updateDisplay();
}

function calculate() {
if (previousInput === '' || currentInput === '') return;
let result;
const prevVal = parseFloat(previousInput);
const currentVal = parseFloat(currentInput);
if (isNaN(prevVal) || isNaN(currentVal)) return;

switch (operator) {
case '+':
result = prevVal + currentVal;
break;
case '-':
result = prevVal - currentVal;
break;
case '*':
result = prevVal * currentVal;
break;
case '/':
if (currentVal === 0) {
currentInput = 'Error';
operator = null;
previousInput = '';
updateDisplay();
return;
}
result = prevVal / currentVal;
break;
default:
return;
}
currentInput = result.toString();
updateDisplay();

// Log calculation to host
sendNotification('notifications/message', {
level: 'info',
data: `Calculated: ${prevVal} ${operator} ${currentVal} = ${result}`
});

operator = null;
previousInput = '';
}

// MCP Communication
let nextId = 1;

function sendRequest(method, params) {
const id = nextId++;
window.parent.postMessage({ jsonrpc: "2.0", id, method, params }, '*');
Copy link
Contributor

Choose a reason for hiding this comment

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

security-medium medium

The use of window.parent.postMessage with a wildcard target origin ('*') is a significant security risk. This allows any page embedding the application in an iframe to receive potentially sensitive messages, leading to data leakage or exploitation. Always specify the exact origin of the parent window instead of '*'. This issue also applies to lines 203 and 214.

Suggested change
window.parent.postMessage({ jsonrpc: "2.0", id, method, params }, '*');
window.parent.postMessage({ jsonrpc: "2.0", id, method, params }, 'https://your-parent-origin.com');

return new Promise((resolve, reject) => {
const listener = (event) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

security-medium medium

The application listens for message events without validating the origin property of the event. This is a security vulnerability as it allows any window or iframe to send messages, potentially leading to spoofing or data manipulation. Always check event.origin and ensure it matches the expected host. Additionally, the sendRequest function adds a 'message' event listener for each request, which could lead to memory leaks if responses don't arrive. Consider implementing a timeout to remove listeners and reject promises.

if (event.data?.id === id) {
window.removeEventListener('message', listener);
if (event.data?.result) {
resolve(event.data.result);
} else if (event.data?.error) {
reject(new Error(event.data.error.message || JSON.stringify(event.data.error)));
}
}
};
window.addEventListener('message', listener);
});
}

function sendNotification(method, params) {
window.parent.postMessage({ jsonrpc: "2.0", method, params }, '*');
}

window.addEventListener('message', (event) => {
const data = event.data;
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

For security, you must verify the message's origin to ensure it's coming from a trusted source. Without this check, your application is vulnerable to attacks from malicious sites. Please add a check for event.origin at the beginning of this event listener. The placeholder origin in the suggestion should be replaced with the actual origin of the parent application.

Suggested change
const data = event.data;
if (event.origin !== 'https://your-parent-origin.com') return;
const data = event.data;

if (data?.method === 'ping') {
// The host sends a 'ping' to check if the app is responsive (liveness check).
// Since this example does not use an MCP SDK, we must manually reply with an empty result
// to acknowledge the ping and keep the connection alive.
if (data.id) {
window.parent.postMessage({ jsonrpc: "2.0", id: data.id, result: {} }, '*');
}
}
});

// Initialize
sendRequest("ui/initialize", {
appCapabilities: {
experimental: {},
tools: { listChanged: false },
availableDisplayModes: ["inline"]
}
}).then((result) => {
console.log("Initialized with host:", result);
sendNotification("ui/notifications/initialized", {});
}).catch(err => {
console.error("Initialization failed:", err);
});

</script>
</body>
</html>
17 changes: 17 additions & 0 deletions samples/agent/mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,23 @@ async def handle_call_tool(name: str, arguments: dict[str, Any]) -> dict[str, An

raise ValueError(f"Unknown tool: {name}")

@app.list_resources()
async def list_resources() -> list[types.Resource]:
return [
types.Resource(
uri="ui://calculator/app",
name="Calculator App",
mimeType="text/html;profile=mcp-app",
description="A simple calculator application",
)
]

@app.read_resource()
async def read_resource(uri: Any) -> str | bytes:
if str(uri) == "ui://calculator/app":
return (pathlib.Path(__file__).parent / "apps" / "calculator.html").read_text()
raise ValueError(f"Unknown resource: {uri}")

@app.list_tools()
async def list_tools() -> list[types.Tool]:
return [
Expand Down
Loading